Django save files from FileField in docker container

I have a model with a FileField. My application is running in a docker container created with a dockerfile. When I save a file it is saved on my local path instead of the containers base root. But when I try to retrieve the file and send it as attachment in an email I get a file not found error. The media root directory is based on the Dockerfile’s base root. The email is built and sent in another container as an async task.
The Dockerfile looks like this:

# pull official base image
FROM python:3.9.1-alpine

# set work directory
#ENV APP_HOME=/code
#RUN mkdir $APP_HOME
#RUN mkdir $APP_HOME/static
#RUN mkdir $APP_HOME/media
#WORKDIR $APP_HOME
WORKDIR /code

# set environment variables
ENV PYTHONDONTWRITEBYTECODE 1
ENV PYTHONUNBUFFERED 1

COPY requirements.txt /code/

RUN apk --update --upgrade --no-cache add 
    postgresql-libs make gdal-dev geos-dev g++ python3-dev cairo-dev pango-dev gdk-pixbuf-dev ttf-ubuntu-font-family

RUN 
    apk add --virtual .build-deps gcc musl-dev postgresql-dev jpeg-dev zlib-dev libffi-dev && 
    pip3 install --no-cache-dir -r /code/requirements.txt && 
    apk --purge del .build-deps

COPY entrypoint.sh /entrypoint.sh
RUN chmod +x /entrypoint.sh

# copy project
COPY . /code/

I have a docker-compose file to build the image and run the container. It looks like that:

version: "3.9"

services:
  db:
    image: postgis/postgis:13-3.0-alpine
    volumes:
      - postgres_data:/var/lib/postgresql/data/
    # TODO remove ports for production
    ports:
      - "5432:5432"
    environment:
      - POSTGRES_DB=GardreamApi
      - POSTGRES_USER=GardreamApi
      - POSTGRES_PASSWORD=gardreamDBUser
  api:
    build: .
    image: gardream/api
    command: python manage.py runserver 0.0.0.0:8000 --settings=api.settings.production
    volumes:
      - .:/code
      - static:/code/static
      - media:/code/media
    ports:
      - "8000:8000"
    env_file:
      - ./.env.dev
    depends_on:
      - db
    entrypoint: /entrypoint.sh
  mail:
    image: gardream/api
    command: python manage.py qcluster --settings=api.settings.production
    depends_on:
      - api

volumes:
  postgres_data:
  static:
  media:

Anyone can help how to save the files in the Dockerfile’s base root?

Django Development Company

Meet Django
Django is a high-level Python Web framework that encourages rapid development and clean, pragmatic design. Built by experienced developers, it takes care of much of the hassle of Web development, so you can focus on writing your app without needing to reinvent the wheel. It’s free and open source.

Meet Steelkiwi
Steelkiwi is a python development company. We offer high-quality web solutions in this programming language that goes along with Django development. Build your ideas faster and easier with Python & Django Web Development Services

#python development company #django development company #web development company #mobile development company

Unable to create a django project with 2 apps in it

When I run the server it shows this error:

This error

and my code link https://github.com/ARGAMERX/django-problem
the whole code is not available as python files but as zip file the main files in which error is occoring is available so you don’t need to download it to read that

view – fields do not recognise django

I have been having a problem working with formsets in my project and I’ve been trying to get to the bottom of this. While doing so, a couple of different errors have been appearing. Generally, what I want to do is create an object of entity A (workout) and get redirected to a template/url that lets me “fill” it with objects of entity B, which I will be making at that point dynamically using model formsets. The problem seems to be revolving around the form, more specifically: if I write the fields one by one, as in :

CycleFormSet = modelformset_factory(
    Cycle, fields=('reps', 'place_in_workout', 'exercise', 'number_of_times', 'break_inbetween'), extra=1
)

Then, I get the error: Unknown field(s) (place_in_workout, break_inbetween, reps, number_of_times) when I attempt to run the server. If I use exclude for some field, or do fields = ‘all‘ , then I don’t get an error at this point. However, I get the error : (‘ManagementForm data is missing or has been tampered with’) when I try to post the data of the workout object. Me code:

models.py

class Exercise(models.Model):
    name = models.CharField(max_length=150)
    description = models.TextField(max_length=500)

    def __str__(self):
        return self.name


class Workout(models.Model):
    name = models.CharField(max_length=150, null=True)
    created_by_user = models.ForeignKey(User, null=True, on_delete=models.RESTRICT)
    description = models.TextField(max_length=1000, null=True)
    created_at = models.DateTimeField(auto_now_add=True)

    def __str__(self):
        return self.name


class Cycle(models.Model):
    place_in_workout = models.IntegerField
    exercise = models.ManyToManyField(Exercise)
    number_of_times = models.IntegerField
    reps = models.IntegerField
    break_inbetween = models.IntegerField
    workout = models.ManyToManyField(Workout)


class WorkoutCompleted(models.Model):
    datetime = models.DateTimeField(auto_now_add=True)
    user = models.ForeignKey(User, on_delete=models.RESTRICT)

forms.py

class CreateUserForm(UserCreationForm):
    class Meta:
        model = User
        fields = ('username', 'email', 'password1', 'password2')


class WorkoutForm(forms.ModelForm):
    class Meta:
        model = Workout
        fields = ('name', 'description')


class ExerciseForm(forms.ModelForm):
    class Meta:
        model = Exercise
        fields = ('name', 'description')


CycleFormSet = modelformset_factory(
    Cycle, fields='__all__', extra=1
)

urls.py

urlpatterns = (
    path('register/', views.register_page, name='register'),
    path('login/', views.login_page, name='login'),
    path('logout', views.logout_page, name='logout'),

    path('', views.index, name='index'),
    path('browse/', views.browse, name='browse'),
    path('workouts/<str:user_id>/', views.workouts, name='workouts'),


    path('add_exercise/', views.add_exercise, name='add_exercise'),
    path('create_workout/<str:user_id>/', views.fill_workout, name='fill_workout')
)

views.py

@login_required(login_url='login')
def workouts(request, user_id):
    context = {}
    if request.method == 'POST':
        form = WorkoutForm(request.POST)
        if form.is_valid():
            workout = form.save(commit=False)
            workout.created_by_user = request.user
            workout.save()
            workout_id = workout.id
            context = {'workout_id': workout_id}

        return render(request, 'Trainmate/fill_workout.html', context)

    else:
        form = WorkoutForm()
        workout_programs = Workout.objects.all()
        user_workouts = workout_programs.filter(created_by_user=user_id)
        context = {'user_workouts': user_workouts, 'form': form}
        return render(request, 'Trainmate/workouts.html', context)


@login_required(login_url='login')
def fill_workout(request, user_id):
    if request.method == 'POST':
        # workouts = Workout.objects.filter(created_by_user__exact=request.user).order_by('-created_at')
        # current_workout = workouts(0)
        # pk_workout = current_workout.id
        pk_workout = 1
        formset = CycleFormSet(request.POST)
        if formset.is_valid():
            for form in formset:
                cycle = form.save(commit=False)
                cycle.workout = Workout.objects.get(pk=pk_workout)
                cycle.save()
        context = {}
        return render(request, 'Trainmate/home.html', context)
    else:
        formset = CycleFormSet(queryset=Cycle.objects.none())
        context = {'formset': formset}
    return render(request, 'Trainmate/fill_workout_with_sets', context)

(there are more views, I didn’t include some views about login/logout, if asked, I will, I didn’t want to make the post even bigger than it’s already going to be). Also, I have run the views with the commented section, I believe I am doing some mistake with queryset, therefore I gave the pk_workout=1 so that the fault in the query set is not relevant. There is at least a workout object in the database at all times.

workouts.html

{% extends 'Trainmate/main.html' %}

{% block content %}
<h1>My Workouts</h1>

<div>
    {% for workout in user_workouts %}
        <tr>
            <td>{{ workout.name }}</td>
            <td><a class="btn btn-sm btn-info" href="">Update</a></td>
            <td><a class="btn btn-sm btn-info" href="">Delete</a></td><br>
        </tr>
    {% endfor %}
</div>

<h1>Create new Workout</h1>
<form method="POST" action="{% url 'fill_workout' request.user.id %}">
    {% csrf_token %}
    {{ form }}
    <input type="submit" value="Create Workout">
</form>
{% endblock %}

fill_workout.html

{% extends 'Trainmate/main.html' %}

{% block content %}

<h1>Fill workout with sets</h1>

    <form id="form_container" method="POST" action="">
        {% csrf_token %}
        {{ formset.management_form }}
        {% for form in formset %}
        <div class="set_form">
            {{ form.as_p }}
        </div>
        {% endfor %}
        <button id="add-form" type="button">Add another set</button>
        <button type="submit"> Create Cycle</button>
    </form>

let set_form = document.querySelectorAll(".set_form")
let container = document.querySelector("#form_container")
let add_button = document.querySelector("#add_form")
let total_forms = document.querySelector("#id_form-TOTAL-FORMS")

let form_num = set_form.length -1

add_button.addEventListener('click',add_form)

function add_form(e){
    e.preventDefault()

    let new_form = set_form(0).cloneNode(true)
    let form_regex = RegExp(`form-(\d){1}-`,'g')

    form_num ++
    new_form.innerHTML = new_form.innerHTML.replace(form_regex, `form-${form_num}-`)
    container.insertBefore(new_form, add_button)

    total_forms.setAttribute('value', `${form_num + 1}`)
}



{% endblock %}

I tried to run the server and complete the form with the name and description of the workout object without the javascript part of the template above, I still get the same error.

Sorry for the long post and the , I have been trying to narrow down my problem as much as I can before posting, but it seems I get nowhere.

Heroku Redis with Django Channels no longer works after removing h username

I have been using Heroku Redis to power Django Channels for a while. My old, existing implementation works. I tried to set up a new app in the pipeline, but when I provision a new Heroku Redis resource it generates it without a username. When I try to use that URI to connect Channels it gives me a 104 error. I can swap the URI with the URI from my old app and it functions, so I’m sure it’s the new addon causing the problems. I’ve tried resetting the credentials and it did not fix the problem. I’ve also tried updating the packages

How do I get Channels to connect using a URI with no username? Can I force a username? Can I force an old version of Redis that has the username?

What makes LINQ (C#) unique compared to another DSL such as Django query syntax?

My question to the community is this:

What makes C#’s LINQ Unique from other query language in other languages and frameworks, or does it not have anything to make it unique at this point?

Specifically with regard to Django or Laravel, but that doesn’t matter all that much. I’m not looking for an opinion of why someone might like it more but rather if there is any concrete difference between them that a general developer would be inclined to choose one over the other because of that difference.

Thoughts

Before I posted this I found this SE post (Python Unique Characteristics), that talks about it may be rather hard to find something that is actually unique. Which is a valid point, however the reason I ask is because I know a lot of .NET developers that use LINQ as a main selling point of .NET (myself included). However, when thinking about it more in depth I don’t know if it is a valid argument anymore which is more what I’m trying to accomplish with this question.

What follows is context

My coworker and I were debating on the reason why LINQ (in the context of C#) could be an argument to use C# over another language. Especially when it can be compared to other DSLs like it (At least I believe it’s a kind of DSL, could be wrong though). We could not actually think of any concrete reason why LINQ would have any distinct advantage, feature or unique oddity over any other query syntax in a modern language or framework. The closest I could come up with was that you could write an underlying driver for LINQ to allow it to theoretically work with just about any data system out there, but the argument could me made that other languages support stuff like that as well.

Part of this question is due to an on going internal discussion between our devs about the merits of C# vs Django, but that is an entirely other area not for the scope of this question.

General Information

The following are some locations where I have been looking to try and find information at least from more official sources.

jquery – How to get ajax data in django views?

Here I simply want to get data from ajax call in my django views. I am using type GET ajax call for my purpose. I dont know how to get data from that into my django views. And right now test varible is also not printing in console.log ,I am newbie please tell me how can i fix all that.

<span class="test">yes</span>

ajax call

   <script>
    /*
    On focus out on input nickname,
    call AJAX get request to check if the nickName
    already exists or not.
    */
    $(".test").focusout(function (e) {
        e.preventDefault();
        // get the nickname
        var text = $(this).text();
        // GET AJAX request
        console.log('test hoon')
        console.log(text)

        $.ajax({
            type: 'GET',
            url: "{% url 'dashboard' %}",
            data: {"text": text},
            success: function (response) {
                // if not valid user, alert the user
            },
            error: function (response) {
                console.log(response)
            }
        })
        
    })
</script>

Views.py

 class Dashboard(TemplateView):
        template_name = "dashboard.html"
    
        def get(self,*args, **kwargs):
            amount = self.request.GET.get('text')
            print("I m here !",amount)
            return render(amount,'dashboard.html',)

Django: Won’t Delete Post – Stack Overflow

I am trying to get my posts to delete on the click of a button that pops up on the screen instead of sending the user to a different delete page. The form works but it won’t actually delete the posts. What am i doing wrong here

Stack Overflow says im using too much code so ignore the next few lines. too much code too much code too much code too much code

Some relevant info:

templates:

{% block head %}

<head>
    <link rel="stylesheet" type="text/css" href="{% static 'css/my_posts.css' %}">
    <title>Create - My Posts</title>

    <script>
        function togglePopup(){document.getElementById("popup-1").classList.toggle("active")}
    </script>

</head>

{% endblock head %}


{% block content %}
<div class="content_section">
    <div class="btn_container">
        <a class="new_post" href="{% url 'newpost' %}"><button class="new_post_btn">New Post</button></a>
    </div>
    <div class="content_section_two">
        {% for product in products %}
            <div class="post_short_container">
                <div class="title_container">
                
                    <a href="#" class="post_link">
                        <div><b>{{ product.title }}</b></div>
                    </a>
                    
                </div>
                <div class="right_btns">
                    <a href="{% url 'editpost' product.id %}" class="edit_link">Edit</a>
                    <a href="#" class="stats_link">Stats</a>
                    <div class="ad_btn_container">
                        <div class="ad_btn">Ad</div>
                    </div>
                    <div class="delete_btn_container">
                        <div class="delete_btn" onclick="togglePopup()">Delete</div>
                    </div>
                </div>
            </div>

            <div class="delete_prompt_container" id="popup-1" action="{% url 'deletepost' product.pk %}">
                <form method="POST">
                    {% csrf_token %}
                    <p class="delete_prompt">Are you sure you want to delete this post?</p>
                    <div class="cancel_delete_container">
                        <div class="cancel_button" onclick="togglePopup()">Cancel</div>
                        <input value="Delete" type="submit" name="confirm" class="confirm_delete_button">
                    </div>

                </form>
            </div>
        {% endfor %}
    </div>

</div>



{% endblock content %}

views.py:

def deletePost(request, pk):
    post = Post.objects.get(id=pk)
    if request.method == 'POST':
        post.delete()
        return HttpResponseRedirect(reverse('myposts'))

urls.py:

urlpatterns=(
    path('deletepost/<int:pk>', views.deletePost, name='deletepost'),
)

python – DJANGO: Set logged-in USER in a Form requiring Current User Credentials

Currently, I can set the the current_user in the views.py for a form, which requires the user object to validate the post (and its origin).

Is there a better way to more eloquently set the user in a form than what I’ve posted below? Note, this is in views.py and I have no altered forms or models to tackle this aspect.

def index(request):
    article = Article.objects.all()
    if request.method == 'POST':
        form = ArticleForm(request.POST)
        # This segment below is the focal point of my question:
        if form.is_valid() and request.user.is_authenticated:
            form_object = form.save(commit=False)
            form_object.author = request.user
            form_object.save()
            return HttpResponseRedirect('to somewhere over the rainbow')
    else:
        # stuff

The code works. It just seems gimmicky to use a non-committed form, store it in a variable, alter the form object, then ultimately save it.

Django Serializers running slow to convert JSON

I have 5 different Foreign Key values in 1 model. There are 1800 records in total.

Using AJAX it is necessary to convert the data to JSON format. I can do this with the Serializers library. I use use_natural_foreign_keys = True for Foreign Key values to return string values.

use_natural_foreign_keys = True

  • When i use it; 15 seconds of query
  • When I am not using it; 0.5 second

But I have to use it. Otherwise, I cannot get Foreing Key values when converted to JSON format.

I leave the query here. How can I make queries faster? Thanks in advance.

result=AbcModel.objects.all()
if kapanan_talepler:
     jsons=serializers.serialize('json',result, use_natural_foreign_keys=True)