Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
django authenticaton - Is this a good practice?
Is this a good practice? models.py from django.contrib.auth.models import User User._meta.get_field('email')._unique = True User._meta.get_field('email').blank = False User._meta.get_field('email').null = False I want to make it happen, that every email is only used once and I found this code example on reddit. Should I instead create an AbstractUser or is that fine? Thanks -
Image is not loading in Django Template
I am having a Django HTML page. I would like to display an image in an HTML file. I am returning like this. in views.py params = { 'obj': obj, 'data':data, } return render_to_string('records/record.html', params), obj In html file <img src="{{data.image.path}}"> While logging what I am getting data.image.path like this https://document.s3.amazonaws.com/others/path/20220809-150420-Screenshot-%2897%29.png?Amz-Expires=600&X-Amz-SignedHeaders=host&X-Amz-Signature=6037f61de9173fcf2a2b556ef81e But it replacing & to &amp in html. -
Django project foundation practices
I am planning to create a product(assume it to be similar to linkedin) and I want to understand what practices I should follow or keep in mind while developing this. I have seen projects in django/flask go messy very quickly. I know this is a very open-ended question but it would be helpful if someone can help me here. -
django how can I use multiprocessing in a management command
how can I use multiprocessing in a django management command? I can't figure out how to start the process inside of my websites django context management command users = users.objects.filter(is_active=True) with ProcessPoolExecutor(max_workers=5) as executor: processes = [] for user in users: p = executor.submit(complex_user_calculation,user) processes.append(p) for f in concurrent.futures.as_completed(processes): result = f.result() if result: print(result) when I run this management command I get this error raise AppRegistryNotReady("Apps aren't loaded yet.") django.core.exceptions.AppRegistryNotReady: Apps aren't loaded yet. ... File "C:\Users\user\AppData\Local\Programs\Python\Python310\lib\concurrent\futures\_base.py", line 390, in __get_result raise self._exception concurrent.futures.process.BrokenProcessPool: A process in the process pool was terminated abruptly while the future was running or pending. -
How to display all child category from parent category in django-rest-framework
I'm trying to show my all children category from parent category. I want to just hit one API end and show all tables which is related to that item. I want to hit "Master-Category" and show all releated "Category","Sub-Category" and "Root-Item" in Hierarchy form. I display all the data but cannot in Hierarchy form. Can anyone please give me the solution for this problem. Model.py from django.db import models from django.contrib.auth.models import User class MasterCategory(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, null=True, blank=True, verbose_name="Created By") title = models.CharField(max_length=100, null=False, blank=False) description = models.TextField(default='') def __str__(self): return str(self.title) @property def category(self): data = NewCategory.objects.filter(master_category__id=self.id).values return data @property def sub_category(self): data = NewSubcategory.objects.filter(category__id=self.id).values return data @property def root_item(self): data = Rootitem.objects.filter(sub_category__id=self.id).values return data class NewCategory(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, null=True, blank=True, verbose_name="Created By") title = models.CharField(max_length=100, null=False, blank=False) description = models.TextField(default="") master_category = models.ForeignKey( MasterCategory, on_delete=models.CASCADE, null=True, blank=True) def __str__(self): return str(self.title) class NewSubcategory(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, null=True, blank=True, verbose_name="Created By") title = models.CharField(max_length=100, null=False, blank=False) description = models.TextField(default="") category = models.ForeignKey(NewCategory, on_delete=models.CASCADE, null=True, blank=True) def __str__(self): return str(self.title) class Rootitem(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, null=True, blank=True, verbose_name="Created By") title = models.CharField(max_length=100, null=False, blank=False) description = models.TextField(default="") sub_category = models.ForeignKey(NewSubcategory, on_delete=models.CASCADE, null=True, blank=True) … -
How to handle this error when referring to an image?
Hey there I have a problem with my header images of my blog post. Every time the page refers to the image this error appears Here is my definition of the Post: class Post(models.Model): id = models.UUIDField( primary_key=True, default=uuid.uuid4, help_text="Unique ID for this specific post across all blog post.", ) title = models.CharField(max_length=200, unique=True) caption = models.CharField(max_length=200, unique=True) category = models.IntegerField(choices=CATEGORY, default=1) header_image = models.ImageField(null=True, blank=True, upload_to="imgs/blog") author = models.ForeignKey( User, on_delete=models.CASCADE, related_name="blog_posts" ) body = RichTextField(blank=True, null=True) created_on = models.DateTimeField(blank=True, null=True) status = models.IntegerField(choices=STATUS, default=0) updated_on = models.DateTimeField(auto_now=True) context_object_name = "post_list" def __str__(self): return self.title def getCategoryStr(self): return CATEGORY[self.category][1] def save(self, *args, **kwargs): if self.status == 1 and self.created_on is None: self.created_on = timezone.now() super(Post, self).save(*args, **kwargs) can anybody please help me. Thank you a lot in advance! -
JQuery Ajax success function not able to access Django View jsonresponse from view
My View class MusicianLikesView(DetailView): model = Musician template_name = "guitar_blog/blog_detail.html" def post(self, request, **kwargs): song = self.get_object() user_id = request.user.id user_username = request.user.username if request.user.is_authenticated: if "Like1" in request.POST and user_username not in song.music_1_users.keys(): song.music_1_votes += 1 song.music_1_users[user_username] = user_id song.save() return JsonResponse({"likes": song.music_1_votes}) elif "Unlike1" in request.POST and user_username in song.music_1_users.keys(): song.music_1_votes -= 1 song.music_1_users.pop(user_username) song.save() return JsonResponse({"likes": song.music_1_votes}) My Urls path('ajax/', MusicianLikesView.as_view(), name="song_likes"), My Template <form method="post" class="voting-setup top_song"> {% csrf_token %} {% if user.get_username in musician.music_1_users %} <button name="Unlike1" type="submit" class="like-button"> <i class="fa-solid fa-guitar icon" ><span class="like-text">Unlike</span></i > </button> {% else %} <button name="Like1" type="submit" class="like-button"> <i class="fa-solid fa-guitar icon" ><span class="like-text">Like</span></i > </button> {% endif %} </form> <span class="after-like first_song_likes">Liked {{ musician.music_1_votes }}</span> My Javascript File $(document).on("submit", ".top_song", function (event) { event.preventDefault(); $.ajax({ type: "POST", url: "ajax/", data: { csrfmiddlewaretoken: "{{ csrf_token }}", }, success: function (response) { console.log(response); }, error: function (re) { console.log(re); } }); }); My Error in Console POST http://127.0.0.1:8000/guitar_blog/20/ajax/ 404 (Not Found) My Changes in View def musician_likes_view(request, pk): song = Musician.objects.get(pk=pk) user_id = request.user.id user_username = request.user.username if request.user.is_authenticated: if "Like1" in request.POST and user_username not in song.music_1_users.keys(): song.music_1_votes += 1 song.music_1_users[user_username] = user_id song.save() return HttpResponse(song.music_1_votes) elif "Unlike1" in … -
How to upload custom data (like Wave height, wind speed and etc) on Mapbox studio from our backend and show it on Flutter application
We are creating a mobile application in Flutter where we have to show ocean routes, wind speed and wave heights in the map with our own data. We explored MapBox documentation and we were not able to find an API which would upload all this data (wind speed, wave height, etc) to the mapbox studio template we created. We have our own database, what we want is to upload this data on the MapBox Studio and show it on our Mobile Application in Flutter. -
Display the history of an object in two apps together in django admin
I have two apps (profiling and ticketing) the ticketing app has three models in names of member,ticket,comment, and the profiling app has one model in name of profile. I do some changes on an profile object via profiling app it displays on profile model history but if I change that object via "inline" from another model the history displays on that model not profile model. I want that history will be displays completly in two models. -
how to set same unique primary key in each model of app according to user in django
i have used custom user model in my django app, first model which has been made by inheriting abstractbase user which i have rendered as a signup form, now i have created another model which i want to render after user signup in his/her profile, now i am stuck at how to assign same unique primary key in another model which i want to render after user signup, so i can access fields from both models. from django.db import models from django.contrib.auth.models import BaseUserManager, AbstractBaseUser,PermissionsMixin class jobglobeluserManager(BaseUserManager): use_in_migrations = True username = None def create_user(self, email=None, password=None, **extra_fields): user = self.model(email=self.normalize_email(email)) user.set_password(password) user.save(using=self._db) return user def create_superuser(self, email=None, password=None, **extra_fields): extra_fields.setdefault('is_staff', True) extra_fields.setdefault('is_superuser', True) extra_fields.setdefault('is_active', True) extra_fields.setdefault('is_admin', True) if extra_fields.get('is_staff') is not True: raise ValueError('Superuser must have is_staff=True.') if extra_fields.get('is_superuser') is not True: raise ValueError('Superuser must have is_superuser=True.') return self.create_user(email, password, **extra_fields) class jobglobeluser(AbstractBaseUser,PermissionsMixin): userid = models.AutoField(primary_key=True) joined_on = models.DateTimeField(auto_now_add=True) is_staff = models.BooleanField(default=False) is_superuser = models.BooleanField(default=False) is_active = models.BooleanField(default=True) is_admin = models.BooleanField(default=False) useris = models.CharField(max_length=30) FirstName = models.CharField(max_length=20) LastName = models.CharField(max_length=20) email = models.CharField(unique=True,max_length=100) code = models.CharField(max_length=20) mobile = models.CharField(max_length=13) country = models.CharField(max_length=30) state = models.CharField(max_length=30) city = models.CharField(max_length=30) Gender = models.CharField(max_length=20) password = models.CharField(max_length=20) password2 = models.CharField(max_length=20) resume = … -
Trouble getting a Django Form to render
Wondered if someone could help me with what I am doing wrong. I wish to present an order form in Django where a customer will only ever fill in an order, they will never need to retrieve an existing order. So I think I only need a POST method and no GET method. When I try to render a url with a form, I get a 405 response. In my views.py file where I think I am making a mistake I have: class RequestReport(View): def post(self, request, *args, **kwargs): form = CustomerOrderForm(data=request.POST) if form.is_valid(): form.save() return render( "order.html", { "form": CustomerOrderForm() } ) And in my app urls file I have: urlpatterns = [ path('', views.RequestHome.as_view(), name='home'), path('order', views.RequestReport.as_view(), name='order'), path('blog', views.RequestBlog.as_view(), name='blog'), path('<slug:slug>/', views.PostDetail.as_view(), name='post-detail'), ] And finally in my order.html file I have: <form action="" method="post"> {% csrf_token %} {{ form.as_p }} <input type="submit" value="Submit" class="report-buttons"> </form> I know that the Customer Order Form is fine because if I insert this in my view it renders correctly class RequestReport(CreateView): form_class = CustomerOrderForm template_name = 'order.html' success_url = "about" but I want to be able to post the form. Appreciate any help. -
How to Add field with default value, without triggering full rewrite of table?
I want to add new field in existing model current Model class InfoModel(models.Model): id = models.UUIDField(default=uuid.uuid4) New Model where I want to add new field count class InfoModel(models.Model): id = models.UUIDField(default=uuid.uuid4) count = models.IntegerField(default=0) this model creates following migration file from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('info', '0001_auto_20220303_1048'), ] operations = [ migrations.AddField( model_name='infomodel', name='count', field=models.IntegerField(default=0), ), ] but If I migrate using above migration file it will trigger full table overwrite for existing rows. how can I avoid it? I tried suggestion from documentation https://docs.djangoproject.com/en/4.0/ref/migration-operations/#addfield not sure, If I did it correctly by creating 2 migrations file because after second migration it was still filling default value for existing rows. I want only new entry into model should have default value, existing rows not required. -
django m2m form is not saving although using form.save_m2m()
i have manyToMany relationship with two models: researcher and program class Program(BaseModel): researcher = models.ManyToManyField('researcher.Researcher',blank=True ,verbose_name=_('Researchers')) i was trying to add some researchers to the program so that's what i did: self.object = form.save(commit=False) researchers=[] for uuid in researchers_uuid: researcher=Researcher.objects.get(uuid=uuid) researchers.append(researcher) self.object.bounty_type = bounty self.object.researcher.set(researchers) logger.info(self.object.researcher.all()) ## => 1 self.object.save() form.save_m2m() logger.info(self.object.researcher.all()) ## => 2 the first logger gives me all the researchers, while the other one give me an empty QuertSet so, how can i save an m2m relationship? and what's wrong in my code -
Django - Cannot assign "<Product: Test Product>": "Reply.comment" must be a "Comment" instance
I'm trying to add a commenting and replying system to my products model. I'm getting a Cannot assign "<Product: Test Product>": "Reply.comment" must be a "Comment" instance. error at new_reply = Reply(content=content, author=self.request.user, comment=self.get_object()) views.py: class ProductFeedbackView(DetailView): model = Product template_name = 'store/product_feedback.html' def get_context_data(self , **kwargs): data = super().get_context_data(**kwargs) connected_comments = Comment.objects.filter(product=self.get_object()) number_of_comments = connected_comments.count() data['comments'] = connected_comments data['no_of_comments'] = number_of_comments data['comment_form'] = CommentForm() connected_replies = Reply.objects.filter(comment=self.get_object()) number_of_replies = connected_replies.count() data['replies'] = connected_replies data['no_of_replies'] = number_of_replies data['reply_form'] = ReplyForm() return data def post(self , request , *args , **kwargs): if self.request.method == 'POST': reply_form = ReplyForm(self.request.POST) if reply_form.is_valid(): content = reply_form.cleaned_data['content'] new_reply = Reply(content=content, author=self.request.user, comment=self.get_object()) new_reply.save() return redirect(self.request.path_info) if self.request.method == 'POST': comment_form = CommentForm(self.request.POST) if comment_form.is_valid(): content = comment_form.cleaned_data['content'] new_comment = Comment(content=content, author=self.request.user, product=self.get_object()) new_comment.save() return redirect(self.request.path_info) models.py: class Product(models.Model): author = models.ForeignKey(User, default=None, on_delete=models.CASCADE) title = models.CharField(max_length=120, unique=True) description = models.CharField(max_length=300, blank=True, null=True) class Comment(models.Model): product = models.ForeignKey(Product, on_delete=models.CASCADE, blank=True, null=True, related_name='comments') author = models.ForeignKey(User, on_delete=models.CASCADE, blank=True, null=True,) content = models.CharField(max_length=200, null=True, blank=False) class Reply(models.Model): comment = models.ForeignKey(Comment, on_delete=models.CASCADE) author = models.ForeignKey(User, on_delete=models.CASCADE, blank=True, null=True,) content = models.TextField(null=True, blank=False) -
The timezone application in django is not working even when I have it configured in the settings
The TIME_ZONE of my application in django is currently not working I have been reading about it and what I currently have in the settings of my application corresponds to what is in the django documentation, the configurations are the following: TIME_ZONE = 'Europe/Paris' USE_I18N = True USE_L10N = True USE_TZ = True Now when I try to use timezone.now() , imported from django.utils import timezone , I get this in the following code The output is this As you can see, the timezone.now() brings me a completely different time than it should be, and I test that with date_now . I don't understand why if I'm using TIME_ZONE = 'Europe/Paris' in the application settings it doesn't bring me the exact time of the city. On the other hand a possible solution would be to use this But if I use this I would have to change in all parts of my application to put timezone.localtime(timezone.now()) when according to the documentation just using timezone.now() should work -
Django style active element url in for loop
{% for i in menu_categories %} <a href="{% url 'category' i.slug %}" class="mr-4 font-light{% if i.slug == url_name %}text-emerald-500 text-3xl{% endif %} hover:text-emerald-600"> {{ i.title }} </a> {% endfor %} I was looking for similar questions, but I didn’t check the url in the for loop. What's wrong? -
Can i add a edit button in my list display in django admin page
[I want to add edit button beside price attribute][1] -
Is it possible to save data directly to django without using forms?
If I have a model like this: class SomeClass(models.Model): title = models.CharField(max_length=100) field1 = models.FloatField() field2 = models.FloatField() field3 = models.FloatField() field4 = models.FloatField() field5 = models.FloatField() def __str__(self): return self.title and I have a set of data, for example data_list = ('title', 10, 20, 30, 40, 50) How can I save data directly without asking for input to user, or using forms? thanks -
Django saves as Object (1) instead of value?
Am using ModelChoiceField in form and trying to save the form but it saves as Object (1) and Object (2) instead of data name. I know that i can change that by adding def __str__(self): return self.name to the model, but i dont want to change this as its connected with other things. Is there any other way to attain this without adding str to model ? My model: class TrendingCourse(models.Model): owner = models.ForeignKey(User, on_delete=models.CASCADE) course = models.CharField(max_length=256) course_slug = models.CharField(max_length=256) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now = True) And my form: class MyModelChoiceField(ModelChoiceField): def label_from_instance(self, obj): return obj.name class CourseForm(ModelForm): course_slug = forms.CharField(widget=forms.TextInput({'class': 'form-control'}), required=False) course = MyModelChoiceField(queryset=Course.objects.filter(owner_id=2), widget=forms.Select(attrs={'class': 'form-control form-select', 'data-placeholder':'Select any trending course'})) class Meta: model = TrendingCourse fields = [ 'course', 'course_slug' ] -
Accept only authentificated requests to backend
I have this question. I am quite new in this area. I have web app. This consist of services deployed on Docker engine. The main services/containers are: Frontend : React on Nginx web server Backend (API) : Django, DRF on gunicorn on Nginx For frontend I use Auth0 provider. It works as expected. If user is not authenticated/authorized it is redirected to login page. Now I want also to "secure" my backend that it only would accept authenticated connections from frontend. For backend (Django) I also have CORS enabled (django-cors-headers package), but I still can connect from my browser my-site/api/ and get the response. Does anybody know which strategy should I use. Should I somehow secure it using JWT tokens. Somehow pass it to backend in my request? -
Using OR in if statement to see if either query param present
I am looking to implement a simple filter using a single query param (eg age=gt:40, name=eq:bob). I am wondering if it is possible to check if either name or age is present in the GET request at once? An example might clarify what I'm after: if ('age' or 'name') in request.GET: This will only match when the first one is used. When I hit the endpoint with the query param name it doesn't match true. I know I could do something like: if ('age' in request.GET) or ('name' in request.GET) : but this could grow quite quickly and become ugly. -
Django prefetched attribute returns null value
The requirement is to have subtopics prefetched at the Campaigns queryset as the attribute prefetched_subtopics but it currently returns null Models class SubTopic(Base): name = models.CharField(max_length=100, unique=True) class CampaignSubTopicAssn(HistoryMixin, Base): campaign = models.ForeignKey(Campaign, related_name='subtopic_assn', on_delete=models.CASCADE) subtopic = models.ForeignKey(SubTopic, related_name='campaign_assn', on_delete=models.PROTECT) View def get_queryset(self): return super(CampaignViewSet, self).get_queryset().prefetch_related(Prefetch('subtopic_assn', queryset=CampaignSubTopicAssn.objects.prefetch_related(Prefetch('subtopic', queryset=SubTopic.objects.all(), to_attr='prefetched_subtopics')))) -
CSRF verification failed. Request aborted. in django rest framework
halo i'm working on a project, using drf, but i'm getting CSRF verification failed. Request aborted at first everything was working, but now when i test my api i keep keep getting,CSRF verification failed below is my setting codes REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': ( 'rest_framework_jwt.authentication.JSONWebTokenAuthentication', ), 'DATE_INPUT_FORMATS': [("%Y-%m-%d")], 'DEFAULT_PERMISSION_CLASSES': ( 'rest_framework.permissions.IsAuthenticated' ), 'DEFAULT_PARSER_CLASSES': ( 'rest_framework.parsers.JSONParser', 'rest_framework.parsers.FormParser', 'rest_framework.parsers.MultiPartParser', ), 'DEFAULT_PAGINATION_CLASS': 'rest_framework.pagination.PageNumberPagination', 'PAGE_SIZE': 100 } can anyone help out -
CORS error on React with Django deployed on heroku
I've been trying to use React + Django rest framework I've deployed the API on heroku and configured the settings.py with django-cors-headers, My settings.py: INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'corsheaders', 'rest_framework', 'rest_framework.authtoken', 'rest_framework_simplejwt', 'rest_framework_simplejwt.token_blacklist', 'account', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'corsheaders.middleware.CorsMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'whitenoise.middleware.WhiteNoiseMiddleware', ] CORS_ORIGIN_ALLOW_ALL = True but when I make a post request with React on localhost I get: login:1 Access to XMLHttpRequest at 'myapi' from origin 'http://localhost:3000' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: Redirect is not allowed for a preflight request. My React: const login = async (email, password) => { const response = await createSession(email, password); console.log('login', response.data); const loggedUser = response; const token = response.data.access; localStorage.setItem('user', JSON.stringify(loggedUser)); localStorage.setItem('token', token); api.defaults.headers.Authorization = Bearer ${token}; setUser(loggedUser); navigate('/'); }; -
Django 3.2 formsets - how to filter product by the list of components that belong to this product?
I am trying to create a formset where the user will be able to do the following: Click on the button and display formset that is relevant to this particular product. I want to display all products and all components after page is loaded so user will see which components belong to which products. Once the user will select the product formset will expand and the user will be able to put a number of units. After inserting all numbers of units in all forms user should click Submit and all forms should be saved at once. QUESTION: How to connect components in each formset to button so after expanding it will show components that are related only to this product. I managed to filter components by creating a loop in my initial method but I am not sure how to make it dynamic. My idea was to somehow filter all components in each product based on product slug value in the data-bs-target attribute but I am not sure how to do it. My second question is how can I make 1 formset so the user will need to click submit button only once? class CostCalculatorView(TemplateView): template_name = "cost_calculator.html" def …