Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Rest Framework: incorrect hyperlink on second viewset of same model
I'm trying to provide two distinct APIs using DRF but I'm unable to get the second app to stop creating hyperlinked references based on the first. It's essentially the same problem as Django Rest Framework with multiple Viewsets and Routers for the same object but I'm unable to get it working. app1/urls.py: router = SimpleRouter(trailing_slash=False) router.register(prefix=r'article', viewset=app1.ArticleViewSet, basename=r'article') urlpatterns = [path(f'', include(router.urls)] app2/urls.py: router = SimpleRouter(trailing_slash=False) router.register(prefix=r'published', viewset=app2.ArticleViewSet, basename=r'published') urlpatterns = [path(f'', include(router.urls)] site/urls.py: urlpatterns = [ path('app1/', include('app1.urls')), path('app2/', include('app2.urls')), ] While both viewsets are of the same model, the queryset & serializer for each is different. When I GET an item from /app2/published, it has an app1 URL: "url": "http://localhost:8000/app1/article/5461" What I'm wanting is for items retrieved via app2 to have: "url": "http://localhost:8000/app2/article/5461" From looking at the docs, it appears that providing basename should do what I want, but I'm not having any luck with getting it to work. -
How Do I Have Multiple ModelForms In Django in A SingleView?
I am trying to create A Project where I Have A model Form Which Takes A set of data as Input. However that is not an issue, How Do I Have Multiple Forms of that One single Model Form . I tried Using something like this from .forms import BookForm # Create your views here. def home_page(request): context = {} form = BookForm(request.POST or None) form1 = BookForm(request.POST or None) if form.is_valid(): form.save() if form1.is_valid(): form1.save() context['form']= form context['form1']= form1 return render(request, "home.html", context) But What Happens is the Data passed in the last form is passed in all of the forms. How Do I Implement this in Django Handling multiple forms in single view, which gets submitted on click of a button -
problem with deploying a dajngo project with gunuicorn and ngnix on centos
I followed all things in this digitalocean tutorial deploy with gunicorn,ngnix on centos But still my website is unavailable and I got unable to connect error but when I ping it It responds what is the problem? -
Is it possible to foreign key on bulk_create() Django?
I have the need to create many EVENT objects at once and subsequently create many ARCHIVED_EVENT objects that have a foreign key to their corresponding event. My code looks like something like this: events = [] archivedEvents = [] for _ in range(1000): event = Event(name="Test") archivedEvent = ArchivedEvent(event_id=event.id) archivedEvents.append(archivedEvent) events.append(event) Event.objects.bulk_create(events) ArchivedEvent.objects.bulk_create(archivedEvents) Unfortunately all Archived Events created here have a NULL foreign key to an EVENT. I understand that the primary key for an object is not generated until it is saved to the database. But I save the events before creating the archived events. Am I missing something? Should I refresh the cache before bulk creating the archived events? -
Django detail view
Models class Order(models.Model): user = models.ForeignKey(User, null=True, on_delete=models.CASCADE) quote_choices = ( ('Movie', 'Movie'), ('Inspiration', 'Inspiration'), ('Language', 'Language'), ) quote = models.CharField(max_length =100, choices = quote_choices) box_choices = (('Colors', 'Colors'), ('Crossover', 'Crossover'), ) box = models.CharField(max_length = 100, choices = box_choices) pill_choice = models.CharField(max_length=30) shipping_tracking = models.CharField(max_length=30) memo = models.CharField(max_length=100) status_choices = (('Received', 'Received'), ('Scheduled', 'Scheduled'), ('Processing/Manufacturing', 'Processing/Manufacturing'), ) status = models.CharField(max_length = 100, choices = status_choices) def __str__(self): return f"{self.user_id}-{self.pk}" class Date(models.Model): order_id = models.OneToOneField(Order, on_delete=models.CASCADE) date_added = models.DateField(max_length=100) scheduled_date = models.DateField(max_length=100) service_period = models.DateField(max_length=100) modified_date = models.DateField(max_length=100) finish_date = models.DateField(max_length=100) html template 'date_list.html' <!DOCTYPE html> <html> <head> <h1>Customer Record</h1> <form action="{% url 'accounts:logout-page' %} " method="post"> {% csrf_token %} <button type="submit" name="button">Logout</button> </form> </head> <body> <a class="button" href="{% url 'accounts:create-order' %}">Create</button>&nbsp;&nbsp;&nbsp;&nbsp;</a> {% for Order in order %} {{ Order.id }}&nbsp;&nbsp;&nbsp;&nbsp; {{ Order.user }}&nbsp;&nbsp;&nbsp;&nbsp; {{ Order.quote}}&nbsp;&nbsp;&nbsp;&nbsp; {{ Order.box }}&nbsp;&nbsp;&nbsp;&nbsp; {{ Order.pill_choice }}&nbsp;&nbsp;&nbsp;&nbsp; {{ Order.shipping_tracking}}&nbsp;&nbsp;&nbsp;&nbsp; {{ Order.memo}}&nbsp;&nbsp;&nbsp;&nbsp; {{ Order.status}}&nbsp;&nbsp;&nbsp;&nbsp; <a class="button" href="{% url 'accounts:date-list' %}">View</a>&nbsp;&nbsp;&nbsp;&nbsp; <a class="button" href="{% url 'accounts:update-order' Order.id %}">Update</a>&nbsp;&nbsp;&nbsp;&nbsp; <a class="button" href="{% url 'accounts:delete-order' Order.id %}">Delete</a>&nbsp;&nbsp;&nbsp;&nbsp; {% endfor %} </body> </html> Views. def date_list(request): date = Date.objects.all() context = { 'date': date } return render(request, "date_list.html", context) So I have two models 'Order' and 'Date', I'm actually trying … -
Can load balancing be done on our local website
I have a simple registration website made using django. Now i want to load balance requests on this website which is on localhost. Is this possible if so how? -
Sub-tenant for a tenant in django tenant schemas
I have managed to create a multi tenant system using django tenant schemas and it is working perfectly fine. Now, I want to develop another feature into it and I am not getting how to develop it. So let me explain it with a example. Suppose there's a tenant named ABC on our website (abc.localhost.com). ABC hires another company to handle sales, they have their own tenant setup on my website (salesXYZ.localhost.com). I want ABC and salesXYZ to be connected to each other so that salesXYZ must be able to access ABC's data. Is there anyway I can integrate this? -
Creating another model object alongside with generic CreateView
Here I am trying to register log if the new category has been created. But this is not working.I am using generic View to create the category model now I want to add LogEntry to this model so tried like this but it is throwing error. Exception Type: AttributeError Exception Value: 'CreateCategory' object has no attribute 'object' views class CreateCategroy(SuccessMessageMixin, generic.CreateView): model = Category fields = ['title'] template_name = 'add_category.html' success_url = reverse_lazy('list_category') success_message = 'Created Successfully.' def post(self, request, *args, **kwargs): LogEntry.objects.log_action(user_id=self.request.user.pk, content_type_id=ContentType.objects.get_for_model(self.object).pk, object_id=self.object.pk, object_repr=force_text(self.object), change_message='New Category has been created.', action_flag=1 ) -
Distinguishing The actions of updating and creation in django M2M signals
I wish to do the following. When a new project is created , i want to notify everybody that was assigned to the project that there's a new project available. Here is my simplified project model: class SalesProject(models.Model): sales_project_name = models.CharField(max_length=100) userProfile = models.ManyToManyField('UserProfile', blank=True) history = HistoricalRecords(excluded_fields=['version', 'project_status']) def __str__(self): return self.sales_project_name When a project is being created, i will send out the following signal : def CreateProjectNotification(sender, **kwargs): if kwargs['action'] == "post_add" and kwargs["model"] == UserProfile: for person in kwargs['instance'].userProfile.all(): #some check here to prevent me from creating a notification for the creator or the project Notifications.objects.create( target= person.user, extra = 'Sales Project', object_url = '/project/detail/' + str(kwargs['instance'].pk) + '/', title = 'New Sales Project created') The reason why im using the m2m_changed.connect instead of post_save is because i wish to access the M2M field , UserProfile to send out the notifications. Since the object would not be added to the through table at the point of creation , i can't use the post_save and instead i have to track the changes from the through table . problem With that said , this signal runs as long as the save() function is called and the model which changed … -
Django dynamic list comprehension filtering between dates
I am using comprehension to filter dynamically between multiple from-to date inputs. If one of the two has no value, the search should still work. How can I apply the below logic using django range operator? def mail_search(request): today_date = datetime.now() qs = MailAllocation.objects.filter(cmp_id=cmp_id) """comprehension: build a dictionary and use it for filtering queryset dynamically""" filters = { key: value for key, value in request.POST.items() if key in ['date_from1','date_to1','date_from2','date_to2','date_from3','date_to3'] and value } qs = qs.filter(**filters).order_by('-creation_date') context={ 'dfs_search_results':qs, } return render(request,'mail_search_results.html',context) -
Get value from form in createview
I use a CreateView to create new users, but I want to update an another model in the same time. (add the user to a club) My form : class SignUpFormInvitation(UserCreationForm): club = forms.CharField(label="Club") club_pk = forms.CharField(widget=forms.HiddenInput) username = forms.CharField(max_length=30, required=True, label="Pseudo") first_name = forms.CharField(max_length=30, required=True, label="Prénom") last_name = forms.CharField(max_length=30, required=True, label='Nom') email = forms.EmailField(max_length=254, label='E-mail') password1 = forms.CharField(widget=forms.PasswordInput, label="Mot de passe") password2 = forms.CharField(widget=forms.PasswordInput, label="Mot de passe confirmation") class Meta: model = User fields = [ 'club', 'username', 'first_name', 'last_name', 'email', 'password1', 'password2', ] def __init__(self, *args, **kwargs): super(SignUpFormInvitation, self).__init__(*args, **kwargs) self.fields['club'].widget.attrs['readonly'] = True The field club and club_pk are correctly added to the form. My view : class SignUpViewInvitation(generic.CreateView): """ display the register form for a sportif """ form_class = SignUpFormInvitation success_url = reverse_lazy('user-connexion') template_name = 'utilisateurs/signup.html' def get_initial(self): club = get_object_or_404(Club, token=self.kwargs.get('token')) return { 'club':club, 'club_pk':club.pk, } def form_valid(self, form): club = Club.objects.get(pk=form.instance.club_pk) club.clubs_members.add(self.request.user) return super().form_valid(form) I try to use form_valid to update the club model but this error is returned : 'User' object has no attribute 'club_pk' for this line club = Club.objects.get(pk=form.instance.club_pk) -
How to setup fcm-django properly
I new to push notification, so I'm sorry for this stupid questions and also I'm unclear about some the terminology used in this package. Here I've some question. -Is the server key and fcm api key is same? -do i need to add some extrnal js script ko make this package work properly. if can you please share some guide or pdf or some link which help me to integrate this. -Do i need to add FCM Device manually? Please make me clear about fcm device. -After setup this project, i didn't get any notification to enable or disable push notifications. Here is my setup settings.py INSTALLED_APPS = [ ....... "fcm_django", ] FCM_DJANGO_SETTINGS = { "FCM_SERVER_KEY": "AAAA......:................................................MGC22WxjWHHcKOo" } Note: FCM_SERVER_KEY is server key instead of web api key If i need to add FCM Device how can i add FCM Devices properly, because i didn't know, from where and how to garb all the value for model FCM Device model fields. -
how can i get max latitude - min latitude - max longitude and min longitude point and radius in python django
I want to get max latitude - min latitude - max longitude and min longitude in my radius and them divide 4 parts and get 4 random points in 4 parts radius = 101 latitude = 54.3578545 longitude = 36.417484151 point = Point(float(latitude), float(longitude)) locations = Location.objects.filter(location__equals=(point, D(km=radius))) point.x + d or point.x + d.standard -
neo4j: "NO MODE SPECIFIED!"
I added neo4j to my docker-compose.yml file. It succesfully created, but while docker-compose up file it gives me this two error messages for neo4j: NO MODE SPECIFIED! env variables are populated(think that is not important) and excites with "neo4j exited with code 1" Also, I am adding MODE to environments, but how I see didn't help. that is how my docker-compose.yml looks like: neo4j: image: neo4j:4.0.5 hostname: neo4j container_name: neo4j ports: - "7474:7474" - "7687:7687" volumes: - ./data:/data environment: - NEO4J_dbms_mode=CORE -
Creating A Relationship Between Two User Models
Im building a website which will have teachers and students. Im using the default Django User models and originally ignored Teachers and treated all my Users as Students. Today I began trying to separate my users into Teachers and Students and am having a lot of difficulty. Im obviously missing some fundamental knowledge and have read a lot online but am going around in circles. A teacher can have many students and a student can have one teacher. First I thought Id need separate Student and Teacher models. So everyone now is a User, and I will attach either a Student or Teacher model to each (is this sloppy?). Now for the relationship. I tried creating a relationship between teachers and students within their own models, but it didnt work so I figured id need a separate TeacherStudentRelationship class to hold the relationships. This is my implementation so far: class Student(models.Model): student = models.OneToOneField(User, on_delete=models.CASCADE) def __str__(self): return f'{self.student.username}' class Teacher(models.Model): teacher= models.OneToOneField(User, on_delete=models.CASCADE) def __str__(self): return f'{self.teacher.username}' class TeacherStudentRelationship(models.Model): student = models.ForeignKey(User, on_delete=models.CASCADE) teacher = models.OneToOneField(User, on_delete=models.CASCADE) This doesnt throw any errors, though in Django Admin I can create multiple instances of TeacherStudentRelationship and assign a student to a … -
Is it possible to retrieve 'id' field of objects deleted in Django .delete()?
When executing the following query, is there a mechanism in place to return a list of the 'id's of the objects that have been deleted? >>> MyModel.objects.all().delete() >>> (430, {'myapp': 430}) -
SSL: CERTIFICATE_VERIFY_FAILED
Tried Option didn't work used in app.py os.environ['PYTHONHTTPSVERIFY'] = '0' ssl._create_default_https_context = ssl._create_unverified_context using flask data = report_downloader.DownloadReport( report, output, skip_report_header=False, skip_column_header=False, skip_report_summary=False, include_zero_impressions=True) and trying to get ACCOUNT_PERFORMANCE_REPORT working fine on local system when used tiangolo/uwsgi-nginx-flask:python3.6 as docker base image and deployed giving below error File "/google-analytics/helper_service/service.py", line 328, in sync_google_ads_word_data skip_report_summary=False, include_zero_impressions=True) File "/usr/local/lib/python3.6/site-packages/googleads/common.py", line 405, in Wrapper return utility_method(*args, **kwargs) File "/usr/local/lib/python3.6/site-packages/googleads/adwords.py", line 1268, in DownloadReport output, **kwargs) File "/usr/local/lib/python3.6/site-packages/googleads/adwords.py", line 1540, in _DownloadReport response = self._DownloadReportAsStream(post_body, **kwargs) File "/usr/local/lib/python3.6/site-packages/googleads/adwords.py", line 1614, in _DownloadReportAsStream response = self.url_opener.open(request) File "/usr/local/lib/python3.6/urllib/request.py", line 526, in open response = self._open(req, data) File "/usr/local/lib/python3.6/urllib/request.py", line 544, in _open '_open', req) File "/usr/local/lib/python3.6/urllib/request.py", line 504, in _call_chain result = func(*args) File "/usr/local/lib/python3.6/urllib/request.py", line 1361, in https_open context=self._context, check_hostname=self._check_hostname) File "/usr/local/lib/python3.6/urllib/request.py", line 1320, in do_open raise URLError(err) urllib.error.URLError: <urlopen error [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed (_ssl.c:852)> -
Django admin log table not updating?
Django admin logs were showing fine before but once I deleted them all then it is not adding the logs in the table . The table is empty always . LogEntry.objects.all() it shows all the data before (worked). after I deleted them all with LogEntry.objects.all().delete() and removed this code. Now I tried changing database and performed some CRUD operation but LogEntry table is empty. What might gone wrong ? -
how to update model object's , only one field data when doing serializer.save() in django rest framework?
so heres my serializer class: class HeroSerializer(serializers.ModelSerializer): class Meta: model=Hero fields=['id','name','secret_identity'] and my view : @api_view(['PUT', ]) def api_hero_update(request, name): try: character = Hero.objects.get(name=name) except: return Response(status=status.HTTP_404_NOT_FOUND) serializer = serializers.HeroSerializer(character, data=request.data) message={} if serializer.is_valid(): serializer.save() print(serializer.data) message["success"]="Update Successful" return Response(data=message) return Response(serializer.errors,status=status.HTTP_400_BAD_REQUEST) Let a model object has fields name and secret_identity. and i want to update its name only but the line serializer = serializers.HeroSerializer(character, data=request.data) doesnt allow me to update only , one field . how to update only one field? -
Created an application based on django and wants to read mails of an user (But without presence of user) using graph API
I have an application in Django framework. I want to read mails of an user without it's presence using graph API. I want this functionality for one user only. I came to this solution that if i get mail.read permission from 'application permissions', then it would work. But my admin is not giving this by saying... It will provide access of all user's mails of this organization. So question how i can achieve this functionality, because i don't want to read mails of all users from active directory. I just want this functionality for one user. -
Scarpy stops at middlewares when I include Django Models into pipline.py
My script works well if the pipeline is disabled. My Scrapy bot stop here: 2020-06-15 07:12:23 [scrapy.middleware] INFO: Enabled downloader middlewares: ['scrapy.downloadermiddlewares.httpauth.HttpAuthMiddleware', 'scrapy.downloadermiddlewares.downloadtimeout.DownloadTimeoutMiddleware', 'scrapy.downloadermiddlewares.defaultheaders.DefaultHeadersMiddleware', 'scrapy.downloadermiddlewares.useragent.UserAgentMiddleware', 'scrapy.downloadermiddlewares.retry.RetryMiddleware', 'scrapy.downloadermiddlewares.redirect.MetaRefreshMiddleware', 'scrapy.downloadermiddlewares.httpcompression.HttpCompressionMiddleware', 'scrapy.downloadermiddlewares.redirect.RedirectMiddleware', 'scrapy.downloadermiddlewares.cookies.CookiesMiddleware', 'scrapy.downloadermiddlewares.httpproxy.HttpProxyMiddleware', 'scrapy.downloadermiddlewares.stats.DownloaderStats'] 2020-06-15 07:12:23 [scrapy.middleware] INFO: Enabled spider middlewares: ['scrapy.spidermiddlewares.httperror.HttpErrorMiddleware', 'scrapy.spidermiddlewares.offsite.OffsiteMiddleware', 'scrapy.spidermiddlewares.referer.RefererMiddleware', 'scrapy.spidermiddlewares.urllength.UrlLengthMiddleware', 'scrapy.spidermiddlewares.depth.DepthMiddleware'] -
How can I sort data by created month
I am trying to sort data in my database by created month. And show data in my template created only certain month. But the error says that 'datetime.date' is not iterable. Any idea how can I sort data by month? Here is my model: class Area(models.Model): name = models.CharField(max_length=30) class Meta: ordering = ["name"] def __str__(self): return self.name class Report(models.Model): area = models.ForeignKey(Area, on_delete=models.CASCADE, null=True, blank=True) month = models.DateField(default=date.today) def __str__(self): return '{}'.format(self.area) def months(self): return self.month Here is my views.py: def report_list_by_month(request): report = Report.objects.all().distinct('month') context = { 'report': report } return render(request, 'report/report_list_by_month.html', context) Here is my report_list_by_month.html and screenshot: {% for month in report %} <a href="{% url 'users:report-list-sorted-by-month' month.pk %}">{{month.month|date:"F"}}</a> {% endfor %} def sorted_by_month(request, pk): months = Report() months_query = months.month context = { 'month': months_query } return render(request, 'report/report_list.html', context) Here is my report_list.html code and error screenshot: {% for month in month %} {{month}} {% endfor %} -
How to use two ckeditor in same template in Django?
I am trying to develop a ckeditor comment box in Django. I successfully added the comment box. But now I am facing the issue in editing the comment part. What I am trying to do is when the user click on the edit button near to the comment, a modal popup appears and editing should happens there. The issue is the ckeditor is not showing in the modal. Instead of ckeditor a normal text field with data from the database is showing. In the console it showing "editor-element-conflict" error. Is there any solution for this? -
Django: Extending to Other Pages
Something is weird when I try to extend parts of 1 file to other files. I haven't used Django before and I am trying to learn how to do so. I believe I figured out what the problem is, but I'm not sure how to solve it. I believe my problem has to do with the url file. url.py file #1: D:\learning\Django\pages\pages_project\urls.py Code in the file: from django.contrib import admin from django.urls import path, include # new urlpatterns = [ path('admin/', admin.site.urls), path('', include('pages.urls')), # new ] url.py file #2 D:\learning\Django\pages\pages\urls.py urlpatterns = [ path('about/', AboutPageView.as_view(), name='about'), # new path('', HomePageView.as_view(), name='home'), ] I want the top part of this file, to be found in the top part of the other files: Base.html file: Home.html file: About.html file: What I believe the problem is but I am not 100% sure: I believe it has to do with one or both of the URL files, is there a way I can print the location that each of these are looking at? -
Django: save() missing 1 required positional argument: 'self'
I'm trying to override the save method and I think I write exactly what the document said, but get the error from django.db import models class Post(models.Model): name = models.CharField(max_length = 20) lower_name = models.CharField(max_length = 20) def save(self, *args, **kwargs): if not self.lower_name: self.lower_name = self.name.lower() super().save(*args, **kwargs) python version: 3.6.8 django version: 2.2.4