Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django ImportError: cannot import name 'designs' view in Users URLs
I'm using the Cookiecutter-django boilerplate for a project. I'm able to successfully create migrations and migrate but getting an import error that appears when I run server. Here's the traceback: File "/Users/username/Desktop/workspace/project/config/urls.py", line 16, in <module> path("users/", include("project.users.urls", namespace="users")), File "/Users/username/miniconda3/envs/cl/lib/python3.6/site-packages/django/urls/conf.py", line 34, in include urlconf_module = import_module(urlconf_module) File "/Users/username/miniconda3/envs/cl/lib/python3.6/importlib/__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 994, in _gcd_import File "<frozen importlib._bootstrap>", line 971, in _find_and_load File "<frozen importlib._bootstrap>", line 955, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 665, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 678, in exec_module File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "/Users/username/Desktop/workspace/project/project/users/urls.py", line 3, in <module> from project.designs.views import designs, popular ImportError: cannot import name 'designs' Here is the urls.py file referenced above: from django.urls import path from project.designs.views import designs, popular from project.users.views import (user_detail_view, user_redirect_view, user_update_view) app_name = "users" urlpatterns = [ path("~redirect/", view=user_redirect_view, name="redirect"), path("~update/", view=user_update_view, name="update"), path("<str:username>/", view=user_detail_view, name="detail"), path('', popular.top_designers, name='designs_top_designers'), path('<username>/', designs.designer_designs, name='designs_designer_designs'), ] And here's the designs.py file called on line 3 of the urls.py file above: ... from django.contrib.auth.decorators import login_required from django.contrib.auth.models import User from django.core.mail import mail_admins ... ... from ..forms import DesignFlagForm, DesignForm from ..models import Design, DesignFlag, Images … -
How to copy and change a property of many models from a queryset, in batch?
I'm aware that you can force copying an instance of a model by settings its pk to None and saving myModel = MyModel.objects.get(..) myModel.pk = None myModel.save() # -> Creates a new copy What if I want to do this on an entire queryset? MyModel.objects.filter(...) Should I iterate over this and do it one-by-one? Or can this be made more efficiently? Use case: Every time a new user is created, I need to copy a bunch of models and related models that I assign to him by default: def save(self, **kwargs): super(User, self).save(**kwargs) for c in MyModelCategory.objects.filter(mymodel__is_default=True): c.pk = None c.user = self.user c.save() for s in MyModel.objects.filter(category=c): s.pk = None s.user = self.user s.save() -
transfer to heroku impossible
hello the setting in production is impossible explanation I have a problem with heroku when I try to put in production it tells me that the static files does not work that's what i tried since the problem always appear because there is some backage that does not work together i create a venv and i install that library necessary` code requirement.txt(certifi == 2019.6.16, chardet == 3.0 .4, dj-database-url == 0.5.0, Django == 2.2.5 django-heroku == 0.3.1 django-tinymce4-lite == 1.7.5, 19.9.0 gunicorn ==, IDNA = = 2.8, JSMin == 2.2.2, 6.1.0 == Pillow, pipenv == 2018.11.26, psycopg2 == 2.8.3, pytz == 2019.2, requests == 2.22.0, sqlparse == 0.3.0, urllib3 == 1.25.3, virtualenv == 16.7.5, virtualenv-clone == 0.5.3, 4.1.3 == whitenoise) view that she works properly locally I hope she walks in heroku -
Create M2M Relationship in post_save Signal
What is the proper way to create M2M relationships during a post-save signal? I have the below code. It successfully creates two Articles and a Blog but does not save the relationship between the two. from django.db import models from django.db.models.signals import post_save from django.dispatch import receiver class Article(models.Model): title = models.CharField(max_length=250) class Blog(models.Model): title = models.CharField(max_length=250) articles = models.ManyToManyField(Article, blank=True) def set_related_articles(self): article_titles = ['a', 'b'] for title in article_titles: _blog = Article(title=title) _blog.save() self.articles.add(_blog) @receiver(post_save, sender=Blog) def blog_post_save(sender, instance, **kwargs): instance.set_related_articles() -
django-rest-framework, adding 'includes' to list response, with pagination
With an API I am currently working on in django-rest-framework, I am attempting to implement something similar to a feature in the json-api standard. Given a book model: class Book(models.Model): title = models.CharField(max_length=255) author = models.ForeignKey(Author, on_delete=models.CASCADE) publisher = models.ForeignKey(Publisher, on_delete=models.CASCADE) I want to include a parameter in the url, include, which lets the user define if they want to include author and publisher models in the response. The additional gotcha, is I am using limit/offset pagination. Thus, the following url: https://my-api-domain/api/books?limit=5&offset=0&include=authors should return something that looks like: { "count": 152, "next": "https://my-api-domain/api/books/limit=5&offset=5&include=authors" "previous": null, "results": [ {"id": 1, "title": "Book 1", "author": 1, "publisher": 18}, {"id": 2, "title": "Book 2", "author": 2, "publisher": 26}, ... ], "include": { "authors": [ {"id": 1, "first_name": "Author", "last_name": "One"}, {"id": 2, "first_name": "Author", "last_name": "Two"}, ... for all author ids in paged `results` field above ] } } So far, my view looks like: class BookViewSet(viewsets.ModelViewSet): queryset = Book.objects.all() serializer_class = BookSerializer permission_classes = (IsAuthenticated,) pagination_class = LimitOffsetPagination filter_class = BookFilterSet filter_backends = [DjangoFilterBackend] def list(self, request, *args, **kwargs): # Grab include from url parameters include = request.query_params.get('include', None) # Apply incoming filters to books queryset = self.filter_queryset(self.get_queryset()) # Apply pagination to … -
How do I refrain from showing repeat datetime data in a django template forloop?
In a django template, I'm accessing objects in a list filtered by the objects' datetime. Here's a current image of the object_list onto an HTML table: The time part of the datetime ("11:50a.m") must remain regardless of duplicates. However, the date part of the datetime ("September 9"), must appear only once for each unique date. Essentially, what I'm looking for would look something like: How would I go about achieving this effect? I've tried using {% if forloop.first %}, but I'm unable to find a way to target all "firsts" of unique dates. This is the current code which corresponds to the first image: {% for event in object_list %} <tr> <td>{{ event.datetime|date:"F j g:ia e" }}: </td> <td><a href="{% url 'detail' event.id %}">{{ event.venue }}</a></td> </tr> {% endfor %} I've also considered not using the date of the datetime object and manually coding the dates in the HTML, but wouldn't know how to eventually tie the DOM date to the object_list according to date. -
Trying to get rid of help text in Django results into error: a list indices must be integers or slices, not str
I am trying to get rid via backend (not with CSS) of help text underneath the user field in a custom User UpdateView. This is my code: class UpdateCustomUser(UpdateView): model = User fields = ['username', 'first_name', 'last_name', 'email'] template_name = 'auth/user_update_form.html' context_object_name = 'current_user' def __init__(self, *args, **kwargs): super(UpdateCustomUser, self).__init__(*args, **kwargs) for fieldname in ['username', 'first_name', 'last_name', 'email']: self.fields[fieldname].help_text = None def get_object(self, queryset=None): return self.request.user Unfortunately, this is the error I get: list indices must be integers or slices, not str I do not understand why this is happening, considering the code I use to get rid of the help text in the user creation form works perfectly and does not throw any error: class CustomUserForm(UserCreationForm): email = models.EmailField(max_length=200, help_text='Required') first_name = models.CharField(max_length=200) def save(self, commit=True): user = super(CustomUserForm, self).save(commit=False) # user.email = self.cleaned_data['email'] if commit: user.save() return user def __init__(self, *args, **kwargs): super(CustomUserForm, self).__init__(*args, **kwargs) for fieldname in ['username', 'password1', 'password2']: self.fields[fieldname].help_text = None class Meta: model = User fields = ('username', 'first_name', 'last_name', 'email', 'password1', 'password2') -
Django office365
How can we add office365 login to our django application login? So I need to add some authentication to my user in django. And similarly how would I be able to use this user in the request parameter. -
How can I add headers to compress statics on a django server in response headers?
Now I am working on site optimization. I use the pagespeed service. Writes that need to compress static files. In the documentation of Django, I found the middleware who is responsible for this, added it. Added file compression headers to request headers. Response headers HTTP/1.1 200 OK Content-Length: 23183 Content-Type: application/javascript Date: Mon, 09 Sep 2019 14:18:34 GMT Last-Modified: Fri, 06 Sep 2019 09:09:22 GMT Server: WSGIServer/0.2 CPython/3.6.8 Request headers Accept: */* Accept-Encoding: gzip, deflate, br Accept-Language: en-US,en;q=0.9,ru;q=0.8 Cache-Control: no-cache Connection: keep-alive Cookie: csrftoken=Lp7qIg3c8hrfWa1GhP2V104Zfem6hz5z63jbLDQHAxxUARRsEgCGZ9pApd4auNfV Host: 22186d6d.ngrok.io Pragma: no-cache Referer: https://22186d6d.ngrok.io/ Sec-Fetch-Mode: no-cors Sec-Fetch-Site: same-origin User-Agent: Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/76.0.3809.132 Safari/537.36 But they need to be added to the response headers, so that pagespeed protects this item. How can I do that? The Django's server is used. Link for check page from pagespeed - https://developers.google.com/speed/pagespeed/insights/?url=https%3A%2F%2F22186d6d.ngrok.io -
Relationship between the client and the company
I have a problem with the relationship between the client and the company. The requirement is this: 1) A client can be a client from many companies. 2) A company can have many clients. class Company(models.Model): name = models.CharField(max_length=30) users = models.ManyToManyField('User') def __str__(self): return self.name class User(models.Model): name = models.CharField(max_length=30) def __str__(self): return self.name I read that this should be a ManyToManyField relationship. But where should it be in the Company model or in the Client model? -
How can I filter manytomany models?
I would like to filter my plots objects on the fruit ex.pear. The Inputs are linked via a manytomany to the plots. This is the structure: This is the data I get out of it: What i would like to have: result: I tried the following: plots = Plot.objects.filter(fruittype__fruit="Pear") inputs = Input.objects.filter(plot__in=plots).distinct() This gives me already a close solution for my problem but not what I want. Now I only would like to filter out the other plots that still show up with apple. -
How to configure a Django application served by uswgi and started by a systemd service?
I'm trying to configure a basic a Django application served by uwsgi so that it can be started from systemd on a CentoS 7.X server. So far my SystemD service is started (active and in running state) but application is not reachable on the configured port. Note that application is running inside a Python virtual environment. Systemd service is active and running uwsgi worker processes are active socket bind to TCP 8003 is in LISTEN state SystemD unit file # /etc/systemd/system/django_03.service [Unit] Description=My Django app Requires=network.target After=network.target After=syslog.target [Service] TimeoutStartSec=0 RestartSec=10 Restart=always User=myuser KillSignal=SIGQUIT Type=notify NotifyAccess=all StandardError=syslog RuntimeDirectory=uwsgi ExecStart=/bin/bash -c 'cd /opt/scripts/django/django_03; source django_03_env/bin/activate; uwsgi --ini /opt/scripts/django/django_03/django_03.ini' [Install] WantedBy=multi-user.target uwsgi configuration file # /opt/scripts/django/django_03/django_03.ini [uwsgi] module = wsgi:application master = true processes = 5 socket = 127.0.0.1:8003 chmod-socket = 664 vacuum = true die-on-term = true Django application # wsgi.py def application(environ, response): response('200 OK', [('Content-Type', 'text/html')]) return [b"Test OK (Django 03) !!"] Thanks for your help -
How do I set up html redirection in google docs?
I am looking for a way to open a file generated by the Django function in Google Documents. For this I use the pydrive library. Now I have a function that forms an html instanse class CvView(AuthorizedMixin, View): """Employee CV view.""" def get(self, request, employee_id, format_): """Returns employee's CV in format which is equal to `format_` parameter.""" employee = get_object_or_404(Employee, pk=employee_id) user = request.user content_type, data = Cv(employee, format_, user).get() if isinstance(data, BytesIO): return FileResponse( data, as_attachment=True, filename=f'cv.{format_}', content_type=content_type) return HttpResponse(data, content_type=content_type) It generates a new html template and opens in a new page of my site. But I need to make sure that the html context (data variable in my function) opens in the user's google docs. To check, I created a new file with the code from pydrive.auth import GoogleAuth from pydrive.drive import GoogleDrive gauth = GoogleAuth() gauth.LocalWebserverAuth() gauth.LoadCredentialsFile(gauth) drive = GoogleDrive(gauth) textfile = drive.CreateFile() textfile.SetContentFile('test.txt') textfile.Upload() and created the client_secrets.json file with Google account access in the same folder. After the direct start of the file I got Authentication successful message. Then I wrapped the code with a function def file_to_gd(file): from pydrive.auth import GoogleAuth from pydrive.drive import GoogleDrive gauth = GoogleAuth() gauth.LocalWebserverAuth() gauth.LoadCredentialsFile(gauth) drive = GoogleDrive(gauth) … -
how to use a column value as a key in json field with django orm and postgres?
I need to find how build a query with django orm I need to find how build a query with django orm I have two tables with a relation one to many. table A id = integer autonumeric data = postgres json ... table B id = integer autonumeric id_A = table A id name = string t_name = string like slug the A.data have a json with the structure {key (t_name of table B): value (is a string value)} so that the definition of entities (name and t_name) are in the table B and the values of that entities ere in the json structure in the table A. eje: Table A id | data 1 |{"a_01":"value a","a_02":"value a","b_01":"value b"} 2 |{"a_01":"value a","b_01":"value b"} Table B id | id_A | name | t_name 1 | 1 | A | a_01 2 | 1 | AA | a_02 3 | 1 | B | b_01 4 | 2 | A | a_01 5 | 2 | B | b_01 the id_A and t_name are uniques together I need to get the items from table A with name (B.name) and value (A.data."t_name") from django orm this query solve my problem but I … -
Advanced queryset sort ordering - won't order as I would like
I'm trying to get a queryset to order in a specific way and can't figure out how to do it. First I'd like it to order by descending end_date - with any empty end_date records grouped first. Then the list should be ordered by the primary field, followed by descending amount. queryset = MyModel.exclude_denied.filter(user=user).order_by( "end_date", "primary", "-amount" ) This is what I currently have but it doesn't quite return it as I'd like it. I want the groups to appear something like this: Items without end_date primary items listed first, then ordered by desc amount Items with end_date primary items listed first, then ordered by desc amount Is trying to create this order just using order_by the appropriate approach? I feel like it's close - but not quite there. I am thinking a better approach would be to create 2 Querysets, then merge them together keeping their order in place. Something like this: Queryset1 = items without end_date, descending primary, then descending amount Queryset2 = items with end_date (desc), descending primary, then descending amount Combine the two Querysets but keeping Queryset1 items listed in order first, then Queryset2 items listed. I'm not sure the best way to accomplish that though, … -
Django: POST Pandas dataframe using API, and Pickle
This is a question building upon How to send a pandas dataframe using POST method and receive it in Hug/other REST API... I believe the answer is not complete and therefore I would like to ask: How do I send the pickled Pandas Dataframe using REST API to a Django Model Database? Below is my try after following the original post, but the object does not save. What do I need to do to make it work? import pandas as pd df = pd.DataFrame({'a': [0, 1, 2, 3]}) import pickle pickled = pickle.dumps(df) import base64 pickled_b64 = base64.b64encode(pickled) Want to send the pickled_b64 object, by POST via API to destination (www.foreignserver.com) import requests r = requests.post('http://www.foreignserver.com/api/DataFrame/', data = {'df_object':pickled_b64}) On Server www.foreignserver.com class DataFrame(models.Model): df_object = models.BinaryField() result: [09/Sep/2019 13:23:53] "POST /api/DataFrame/ HTTP/1.1" 201 64 In Django REST framework HTTP 200 OK Allow: GET, PUT, PATCH, DELETE, HEAD, OPTIONS Content-Type: application/json Vary: Accept { "url": "http://www.foreignserver.com/api/DataFrame/17/", "df_object": "" } -
Select users from list and add to post request
I have a list of users that all have checkbox next to them. All the users that are selected should be added to the array and then sent to the database via the django post request. Here is a picture of that: The Button at the bottom is the submit button. models: class UserProfile(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) color = models.CharField(max_length=25, default="", blank=True) class Studyplan(models.Model): name = models.CharField(max_length=100, null=True) description = models.CharField(max_length=1000, null=True) parent_assignment = models.ForeignKey(Assignment, blank=True, on_delete=models.CASCADE,related_name="studyplan", null=True) deadline = models.DateField(default=date.today, null=True) students = models.ManyToManyField(UserProfile, blank=True, related_name="studyplan_students", null=True) teachers = models.ManyToManyField(UserProfile, blank=True, related_name="studyplan_teachers", null=True) canview = models.ManyToManyField(UserProfile, blank=True, related_name="studyplan_canview", null=True) notes = models.ManyToManyField(Note, blank=True, related_name="studyplan", null=True) tasks = models.ManyToManyField(Task, blank=True, related_name="studyplan", null=True) messages = models.ManyToManyField(Message, blank=True, related_name="studyplan", null=True) Views: @login_required def skapa_studieplan(request): if request.method == 'POST': name = request.POST.get('Studyplan-Name') description = request.POST.get('Studyplan-Description') parent_assignment = Assignment.objects.get(pk=request.POST.get('Studyplan-PAID')) users = UserProfile.objects.all() instance = Studyplan.objects.create(request.POST.get('Studyplan-Canview')) for user in users: instance.canview.add(user) studyplan = Studyplan(name=name, description=description, parent_assignment=parent_assignment, canview=instance) studyplan.save() return redirect('allaStudieplaner') My Problem is that I can't figure out to get the values from a ManyToManyField into a POST request. I get an error similar to this: Direct assignment to the forward side of a many-to-many set is prohibited. Use emails_for_help.set() instead -
how to fix "Amazon S3 CORS configuration in django"
i am having a problem implementing amazon S3 in my Django web app.i uploaded the media files in the s3 bucket. but whenever I visit the web app, the images don't appear. and when I click open image in another location, then I get this message. "This XML file does not appear to have any style information associated with it. The document tree is shown below." thanks. CORS configurations in AWS3 <?xml version="1.0" encoding="UTF-8"?> <CORSConfiguration xmlns="http://s3.amazonaws.com/doc/2006-03-01/"> <CORSRule> <AllowedOrigin>*</AllowedOrigin> <AllowedMethod>GET</AllowedMethod> <AllowedMethod>POST</AllowedMethod> <AllowedMethod>PUT</AllowedMethod> <AllowedHeader>*</AllowedHeader> </CORSRule> </CORSConfiguration> settings.py AWS_ACCESS_KEY_ID="AKIA3YNRVIBTIO6SMLIB" AWS_SECRET_ACCESS_KEY="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" AWS_STORAGE_BUCKET_NAME="izala" AWS_S3_FILE_OVERWRITE=False AWS_DEFAULT_ACL=None DEFAULT_FILE_STORAGE="storages.backends.s3boto3.S3Boto3Storage" INSTALLED_APPS = [ 'storages', ] -
How to get a username instead of an id?
I want to write a tweeter-like app but I have this wierd message when i'm trying to get the author username instead of the author id. I would like to know how to get that author username properly instead of having this error : NOT NULL constraint failed: tweets_tweet.author_id I first tried to use the get_field method in my seriliazer. Here is the model: class Tweet(models.Model): slug = models.CharField(max_length=100, unique=True, null=True, blank=True) content = models.TextField(max_length=150) datestamp = models.DateTimeField(auto_now_add=True) nb_likes = models.PositiveIntegerField(default=0) nb_comments = models.PositiveIntegerField(default=0) author = models.ForeignKey( User, on_delete = models.CASCADE, related_name = "tweets", related_query_name = "post", null=False ) def save(self, *args, **kwargs): self.slug = slugify(self.content[:10]) + '-' + randomString() super(Tweet, self).save(*args, **kwargs) Here is my Serializer : class TweetSerializer(serializers.ModelSerializer): author = serializers.SerializerMethodField() def get_author(self, obj): return obj.user.username class Meta: model = Tweet fields = ["content", "author", "nb_likes", "nb_comments", "slug"] def to_representation(self, obj): representation = super().to_representation(obj) if obj.nb_likes > 50: representation['super_popular'] = True return representation -
Cloning all objects in a table to different table django
I have a (Django/Postgresql) project that has lots of tables with foreignkeys and manytomany fields. I should create new tables derivatives of these tables. I have some restrictions for objects to clone and I should change foreignkeys and manytomany ids because my new tables have relations with each other. You can say that: TableA: Item(TableB) Item(TableC) TableB: Item(TableA) TableC: I should do like: TableA_1: Item(TableB_1) TableB_1: Item(TableA_1) TableC: None What happened is I have changed foreignkeys and remove some items that does not apply to my restrictions. Is there a fast way to do it? I am doing it using django pagination and serializer, then change all foreignkeys and manytomany keys. It is a very slow process. -
Error running inspectdb command for database in redshift
I am working to execute the inspectdb command in redshift. I have installed psycopg2 and django-redshift-backend and when doing the db inspect I get this error: # Unable to inspect table 'TABLE_REDSHIFT' # The error was: syntax error at or near "WITH" LINE 6: FROM unnest(c.conkey) WITH ORDINALITY co... -
django app on apache error: sec_e_invalid_token
Hello guys I'm trying to deploy my django app on apache on windows server 2008 R2 but I'm getting an error curl: (35) schannel: next InitializeSecurityContext failed: SEC_E_INVALID_TOKEN (0x80090308) - The token supplied to the function is invalid. Been stuck with this prob for a while can anyone help me ? -
Django Background tasks vs Celery
I am trying to do some tasks in django that consume alot of time. For that, I will be running background tasks. After some R&D, i have found two solutions: Celery with RabbitMQ. Django Background tasks. Both options seem to fulfill the criteria but setting up Celery will require some work. Now as far as the second option is concerned, setup is fairly simple and in fairly quick amount of time, i can go on writing background tasks. Now my questions if i adopt the 2nd option is this: How well does Django Background tasks perform ? (Scalability wise in Production environment). Can i poll the tasks (after some time) in DB to check the task's status? Architecture of Django-Background-tasks? Couldn't find any clear explanation about it's architecture (Or have I missed some resource?) Again coming to the first point, how well does Django Background tasks perform in production. (Talking about prior experience of using this in prod.) -
Get data from python backend
I'm running web application and i need to call specific python function, that returns some data. I am trying some AJAX, but I am not sure, how to call specific function. Any advice? -
How write django views based on sparql results from an ontolgy?
I have built a Django web application that takes in a textual description of a system. I then used natural language processing to extract specific textual information. The extracted information is then populated (as individuals) into an ontology (.owl) using a Owlready2. Once the ontology is populated, I can run SPARQL queries. Now, I would like to display the query results in a template via class base view. Currently, I dont know where to start with a solution. I can only think of converting the query results to json and the put it in the class based view. Below is some code to get the SPARQL results. from owlready2 import * import owlready2 owlready2.JAVA_EXE = "mypath" world = World() world.get_ontology("file://C:\\mypath\\RDFContext_Test.owl").load() sync_reasoner(world) print(world) graph = world.as_rdflib_graph() r = graph.query(""" PREFIX UC: <http://www.semanticweb.org/name/ontologies/2018/8/untitled-ontology-2#> PREFIX rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#> PREFIX owl: <http://www.w3.org/2002/07/owl#> PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#> prefix xsd: <http://www.w3.org/2001/XMLSchema#> select ?use_case ?flgroup where { ?use_case UC:hasGoal "V" . ?use_case UC:hasFlowGroup ?flgroup. ?flgroup a UC:SpecificAltFlowGroup .}""") However, I dont know where to go from here to display it in the template. Can some point me in the right direction?