Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
lack of foreign key in admin model?
I get the following error when trying to update my database: class 'artdb.admin.RoleInline': (admin.E202) 'artdb.Role' has no ForeignKey to 'artdb.Person' I want ot have a many to many relation between Person and Role model.py (not showing all classes): class Person(models.Model): mail=models.EmailField() firstName=models.CharField(max_length=200) lastName=models.CharField(max_length=200) phoneNumber=PhoneNumberField() streetAdress=models.CharField(max_length=200) zipcode=models.CharField(max_length=200) city=models.CharField(max_length=200,default="Göteborg") country=models.CharField(max_length=200,default="Sweden") def __str__(self): return "%s %s" % (self.firstName,self.lastName) class Meta: ordering = ('firstName','lastName') class Role(models.Model): role=models.CharField(max_length=200) person=models.ManyToManyField(Person) def __str__(self): return self.role class Meta: ordering = ('role',) admin.py (not showing all classes): from django.contrib import admin from .models import Role from .models import Address from .models import Date from .models import Person from .models import Name # Register your models here. admin.site.register(Role) admin.site.register(Address) admin.site.register(Date) admin.site.register(Name) admin.site.register(Person) class RoleInline(admin.TabularInline): model=Role extra=3 class PersonInline(admin.ModelAdmin): fieldsets=[ (None,{'fields': ['mail','firstName','lastName','phoneNumber','streetAdress','zipcode','city','country']}), ] inlines = [RoleInline] search_fields = ['firstName'] #admin.site.register(Name,NameInline) admin.site.register(Person,PersonInline) it has worked before with run manage.py makemigrations artdb I don't see the errorin the models. -
nested serialize filter output in serializer
In this example: class TrackSerializer(serializers.ModelSerializer): class Meta: model = Track fields = ('order', 'title', 'duration') class AlbumSerializer(serializers.ModelSerializer): tracks = TrackSerializer(many=True) class Meta: model = Album fields = ('album_name', 'artist', 'tracks') this output occurs: 'album_name': 'The Grey Album', 'artist': 'Danger Mouse', 'tracks': [ {'order': 1, 'title': 'Public Service Announcement', 'duration': 245}, {'order': 2, 'title': 'What More Can I Say', 'duration': 264}, {'order': 3, 'title': 'Encore', 'duration': 159}, enter code here how Can I define I want just tracks that has orded:1? -
Nginx can't find file i specified using a path
I'm trying to serve a user a file using Nginx and later on when I figured out this problem first, then serve it with a protected url. Right now I have some code which specifies the path to the file the user wants to download. However my browser returns File not found. My views def download_item(request, pk): item = get_object_or_404(Usertasks, pk=pk) output_path = item.OutputPath response = HttpResponse() print(output_path) response["Content-Disposition"] = "attachment; filename={0}".format(output_path) response['X-Accel-Redirect'] = output_path return response My terminal prints out Not Found: /home/django/copypaste/cleanup/var/media/admin/output/123.txt and this path is correct and the filename is 123.txt for testing purposes Nginx sites-enabled config # mysite_nginx.conf # the upstream component nginx needs to connect to upstream django { server unix:///home/django/copypaste/cleanup/usegolem.sock; # for a file socket # server 127.0.0.1:8001; # for a web port socket (we'll use this first) } # configuration of the server server { # the port your site will be served on listen 8000; # the domain name it will serve for server_name 127.0.0.1; # substitute your machine's IP address or FQDN charset utf-8; # max upload size client_max_body_size 250M; # adjust to taste # Django media location /media { alias /home/django/copypaste/cleanup/var/media; # your Django project's media files - amend as … -
django csv file validation in model form clean method
Following is the FileModel to upload a csv file in my Django application: class File(models.Model): uploaded_by = models.ForeignKey( User, on_delete=models.CASCADE, ) csv_file = models.FileField( upload_to='csvfiles/', ) On invocation of the /upload_file url pattern, the upload_csv_file view executes as follows: def upload_csv_file(request): if request.method == 'POST': csv_form = CSVForm(request.POST, request.FILES) if csv_form.is_valid(): file_uploaded = csv_form.save(commit=False) file_uploaded.uploaded_by = request.user csv_form.save() return HttpResponse("<h1>Your csv file was uploaded</h1>") elif request.method == 'GET': csv_form = CSVForm() return render(request, './mysite/upload_file.html', {'csv_form': csv_form}) In forms.py I am validating the following: file extension (.csv) file size (5 mb) class CSVForm(forms.ModelForm): class Meta: model = File fields = ('csv_file',) def clean_csv_file(self): uploaded_csv_file = self.cleaned_data['csv_file'] if uploaded_csv_file: filename = uploaded_csv_file.name if filename.endswith(settings.FILE_UPLOAD_TYPE): if uploaded_csv_file.size < int(settings.MAX_UPLOAD_SIZE): return True else: raise forms.ValidationError( "File size must not exceed 5 MB") else: raise forms.ValidationError("Please upload .csv extension files only") return uploaded_csv_file def clean(self): cleaned_data = super(CSVForm, self).clean() uploaded_csv_file = cleaned_data.get('csv_file') return uploaded_csv_file However i encounter the following error on submitting the file upload button: Attribute error: 'bool' object has no attribute 'get' I am unsure whether the 'def clean_csv_file(self)' is being invoked or not. There are ways to validate file extension and size within the function-based view, but I would like to validate … -
Is it possible to send multiple CSRF protected POST requests without reloading the page (Django)?
I'm creating a single page with a form and an optional login functionality. After the user has logged in (using AJAX) the form's CSRF token becomes invalid (as specified in the Django documentation: https://docs.djangoproject.com/en/2.0/ref/csrf/#why-might-a-user-encounter-a-csrf-validation-failure-after-logging-in). So the page needs to be reloaded to get a new valid CSRF token. But I would like the page not to be reloaded. Is there a common practice to do this? e.g. seperately generate a new token and then send as response after every successful login (AJAX request)? -
How to generate a Django one-time download link
i would like to secure downloadable files in my project but dont know how to accomplish that. Each time the post_detail view get's called a new download link should get generated with a validity of 60 min and which also can only be access ones. models.py class Post(models.Model): author = models.ForeignKey(User, on_delete=models.CASCADE) title = models.CharField(verbose_name="Post Title", max_length=25) content = models.TextField(verbose_name="Post Content", max_length=5000) tag = models.CharField(verbose_name="Tags/Meta - (sep. by comma)", max_length=50, blank=True) category = models.ForeignKey(Category, verbose_name="Category", on_delete=models.CASCADE, null=True) postattachment = fields.FileField( verbose_name="Post Attachment", blank=True, null=True, upload_to=get_file_path_user_uploads, validators=[file_extension_postattachment, file_size_postattachment] published_date = models.DateField(auto_now_add=True, null=True) def publish(self): self.published_date = timezone.now() self.save() class Meta: verbose_name = "Post" verbose_name_plural = "Post(s)" ordering = ['-title'] def __str__(self): return self.title views.py def post_detail(request, pk): post = get_object_or_404(Post, pk=pk) list_comments = Comment.objects.get_queryset().filter(post_id=pk).order_by('-pk') paginator = Paginator(list_comments, 10) page = request.GET.get('commentpage') comments = paginator.get_page(page) return render(request, 'MyProject/post_detail.html', {'post': post, 'comments': comments}) If smb. maybe has some practice example it would be really helpful. Thanks in advance -
Increment object on save
I am trying to increment an object everytime I save it, so that one user can have multiple instances of an object, which I can then call accordingly in an html template. HTML <div class="col-md-6 outer"> <div class="box"> <div class="words"> <div> <p class="ins">{{ goals.instrument }}</p> <p class="date">{{ goals.goal_date }}</p> </div> <div> <br /> <br /> <p>{{ goals.goal }}</p> </div> </div> </div> </div> <div class="col-md-6 outer"> <div class="box"> <div class="words"> <div> <p class="ins">{{ goals1.instrument }}</p> <p class="date">{{ goals1.goal_date }}</p> </div> <div> <br /> <br /> <p>{{ goals1.goal }}</p> </div> </div> </div> </div> models.py class Goals(models.Model): user = models.OneToOneField(User, default=None, null=True, on_delete=models.CASCADE) goal = models.CharField(max_length=2000) instrument = models.CharField(max_length=255, choices=instrument_list, blank=True) goal_date = models.DateField(auto_now=False, auto_now_add=False) def __str__(self): return self.goals @receiver(post_save, sender=User) def create_user_goals(sender, instance, created, **kwargs): if created: Goals.objects.create(user=instance) @receiver(post_save, sender=User) def save_user_goals(sender, instance, **kwargs): instance.goals.save() class GoalsForm(ModelForm): class Meta: model = Goals exclude = ('user',) views.py def goal_creation(request): if request.method == 'POST': form = GoalsForm(request.POST, instance=request.user.goals) if form.is_valid(): goals = form.save(commit=False) goals.user = request.user goals.save() return redirect('/student/goal-progress') else: form = GoalsForm() form = GoalsForm() context = {'form': form} return render(request, 'student/goal_creation.html', context) def goal_progress(request): form = GoalsForm goals = request.user.goals context = {'form' : form, 'goals' : goals} return render(request, 'student/goal_progress.html', context) … -
Cannot dump fixtures for django.contrib.auth. Why does `python manage.py dumpdata auth` return an empty list?
The problem: $ python manage.py dumpdata auth.user [] But I do have users: $ python manage.py shell Python 3.6.8 (default, Dec 24 2018, 19:24:27) [GCC 5.4.0 20160609] on linux Type "help", "copyright", "credits" or "license" for more information. (InteractiveConsole) >>> from django.contrib.auth.models import User >>> User.objects.all().count() 3 And loaddata works fine: $ cat user.json [ { "model": "auth.user", "fields": { "username": "fixture_user" } } ] $ python manage.py loaddata user.json Installed 1 object(s) from 1 fixture(s) My Django version: $ pip show Django Name: Django Version: 1.11.7 My database is a local PostgreSQL database. What could I be doing wrong? -
Unique together constraint for two FK to same model, without order
How could I do a unique_together for a model: class Team(models.Model: user_a = models.ForeignKey(User, related_name='a') user_b = models.ForeignKey(User, related_name='b') And I want to make sure user_a and user_b can't be a duplicate, doesn't matter which order they are. So user_a=1, user_b=2 would constraint user_a=2, user_b=1 also, instead of exact duplicate. Is there a way to do this, without custom logic to check for saving the Team? I'm currently just letting them duplicate, then removing the duplicate fields with a RawSQL query. -
list user contacts based on join in system or not
I have a lot of users in my web service (in django). Each user have some contacts that maybe them join in my service or not. I want to get list user contacts with a field that show each contact was joined in my service or not. I look up for best practice. please help me. -
For loop in Django
I have two question. First question: Python script that shows me the precipitation for a certain period.For example, I'm getting an initial year-month and a final year-month. Initial: year:2000 month:3 Final year1:2005 month:4 Now, instead of seeing: 2000/3,2000/4,2000/5,2000/6..........2005/1,2005/2,2005/3,2005/4 she works like this(look in the hooked picture): 2000/3, 2000/4, 2001/3, 2001/4........2005/3,2005/4. I want to work for me like the first case. def period_month_prec(year,month,year1,month1): for i in range (year,year1+1,1): for j in range(month,month1+1,1): ...................... Second question: How to write the output(picture) from the script in csv.fileenter image description here This is what my views.py script looks like , which saves me only the first result: def monthly_period(request): if request.method == "POST" : form = PeriodMonthlyForm(request.POST) if form.is_valid(): data = form.cleaned_data year = data.get('year') month = data.get('month') year1 = data.get('year1') month1 = data.get('month1') lon = data.get('lon') lat = data.get ('lat') inter = data.get('inter') point = period_month_prec(year,month,year1,month1,lon,lat) args = {'point':point} response = HttpResponse(content_type='text/txt') response['Content-Disposition'] = 'attachment; filename="precipitation.txt"' writer = csv.writer(response) writer.writerow([point]) return response else: form = PeriodMonthlyForm() active_period_monthly = True return render (request, 'carpatclimapp/home.html',{'form':form, 'active_period_monthly': active_period_monthly}) -
How to change an output variable in a form
I want to get the "user", when someone is posting a File. It, works somehow, but still displays an error. i Tryed allready to override the "form_valid" , but i allways get a TypeError. #forms.py class CreateMemesForm(forms.ModelForm): class Meta: model = Meme exclude = ["author"] #models.py class Meme(models.Model): uploaded_at = models.DateTimeField( auto_now_add=True) title = models.CharField(max_length=255) author = models.ForeignKey(CustomUser, on_delete=models.CASCADE, blank=True) file = models.FileField(blank=True, upload_to="memes") #views.py class UploadMemes(LoginRequiredMixin, FormView): form_class = CreateMemesForm template_name = "memes/meme_form.html" def form_valid(self, form): self.object = form.save(commit=False) self.object.author = self.request.user self.object.save() return super(ModelFormMixin, self).form_valid(form) #error i get super(type, obj): obj must be an instance or subtype of type It should get the author as CustomUser object. -
Integrity Error On ManyToManyField Django - Foreign Key
Error django.db.utils.IntegrityError: (1452, 'Cannot add or update a child row: a foreign key constraint fails (django_apollo.jobs_job_users, CONSTRAINT jobs_job_users_jobs_id_2172345a_fk_jobs_id FOREIGN KEY (jobs_id) REFERENCES jobs (id))') views.py # Ajax @login_required def AjaxClockJobCreate(request, user_id): form = JobFormInClock(request.POST, instance=User.objects.get(id=user_id)) user11 = get_object_or_404(User, pk=user_id) print('printing', user11.id) if request.method == "POST" and request.is_ajax() and form.is_valid(): form.instance.job_start_date = datetime.datetime.now() form.instance.job_start_time = datetime.datetime.now() form.instance.job_end_date = datetime.datetime.now() + datetime.timedelta(days=1) form.instance.job_end_time = datetime.datetime.now() + datetime.timedelta(hours=15) form.instance.job_created_on = datetime.datetime.now() form.instance.job_updated_on = datetime.datetime.now() form.instance.job_status = 'Active' form.instance.job_company = request.user.userprofile.user_company form.instance.job_created_by = request.user form.instance.job_updated_by = request.user form.save() form.instance.user_jobs.add(user11.id) # ManyToManyField lastest_entry = Jobs.objects.latest('id') data = { 'job_value': lastest_entry.id, 'job_name': lastest_entry.job_name, 'error_message': 'Could not enter job.' } return JsonResponse(data) Models.py class Jobs(models.Model): job_company = models.ForeignKey(Company, on_delete=models.CASCADE) job_group = models.ForeignKey(Groups, on_delete=models.CASCADE) job_users = models.ManyToManyField(User,related_name='user_jobs', blank=True) job_name = models.CharField(max_length=30) job_number = models.CharField(max_length=30) job_description = models.CharField(max_length=100, blank=True, null=True) job_start_date = models.DateField(blank=True, null=True) job_start_time = models.TimeField(blank=True, null=True) job_end_date = models.DateField(blank=True, null=True) job_end_time = models.TimeField(blank=True, null=True) job_created_on = models.DateTimeField(auto_now_add=True) job_created_by = models.ForeignKey(User, on_delete=models.CASCADE, related_name='job_created_bys') job_updated_on = models.DateTimeField(auto_now=True) job_updated_by = models.ForeignKey(User, on_delete=models.CASCADE, related_name='job_updated_bys') job_is_deleted = models.BooleanField(default=False) job_deleted_at = models.DateTimeField(blank=True, null=True) ACTIVE = 'Active' INACTIVE = 'Inactive' JOB_ACTIVE_CHOICES = ( (ACTIVE, 'Active'), (INACTIVE, 'Inactive'), ) job_status = models.CharField( max_length=8, choices=JOB_ACTIVE_CHOICES, default=INACTIVE, ) class Meta: db_table = "jobs" def __str__(self) : return … -
Tune RabbitMQ Server to handle more request
The scenario is that we are pushing messages in JSON format in bulk to an HTTP end point which we call as the coordinator. The coordinator does two things: Encrypt the message Pushes this message via RabbitMQ and celery to a message broker over TCP. We are able to process 1k requests per second with 2 workers and 8 concurrencies. The configuration of server is 8 CPU 32 GB RAM. The challenge is to tune RabbitMQ to handle around 40k requests per second on the same infrastructure. Our Stack: Django, Python, Celery, RabbitMQ, Mongo, Docker, AWS can this be done ? and How ? -
Django doesn't work with multiple pyplots in template
I try to show multiple histograms in Django template. In the HTML file I have the following code: {% for value, data in histograms %} <div class="col-xs-12 col-md-6"> <img src="{% url 'histogram' %}?value={{ value }}&data={{ data|join:"," }}"> </div> {% endfor %} urls.py: url(r'^histogram.png$', views.histogram, name="histogram"), and, finally, the view: import matplotlib matplotlib.use('Agg') import matplotlib.pyplot as pyplot def histogram(request): data = [float(val) for val in request.GET['data'].split(',')] binwidth = 0.5 fig, ax = pyplot.subplots() ax.hist(data, bins=numpy.arange(min(data), max(data) + binwidth, binwidth)) ax.set_title(request.GET['value']) f = BytesIO() pyplot.savefig(f, format='png') pyplot.clf() pyplot.cla() pyplot.close(fig) response = HttpResponse(f.getvalue(), content_type='image/png') return response Without matplotlib.use('Agg') I get Segmentation fault: 11. Using Agg I get some histograms completely white and others it looks exactly the same even they have different data. Any ideas, please? If I view only one, in the browser, by direct URL (histogram.png?value=25&data=13.37,19.1,20.0,8.9,13.6,14.0,14.6,14.4,12.4,14.9,12.5,12.7,13.6,12.8,13.0,11.0,14.0,14.1,9.5,17.5,14.7,11.6) is shown correctly. -
Django database foreign key limitations
my question is so simple. suppose we have a model that has foreign key field to another model. class B(models.Model): ..... class A(models.Model): foo_b = models.ForeignKey(B, on_delete=models.SET_NULL, null=True) if we have many fields foo_b that related to B model. is this wrong or can slow and cause lag to my database connections or not?performance is more matter here so I need to choose carefully. -
the view didn't return an HttpResponse object. It returned None
For testing my form loggin, in the view index i return a dictionary. When i clicked on the submit button i receive this message error : The view accueil.views.index didn't return an HttpResponse object. It returned None instead. Where i made a mistake? def index(request): formConnex = ConnexionForm() if request.method=='POST': formConnex =ConnexionForm(request.POST) if formConnex.is_valid(): envoi = True surnom = formConnex.cleaned_data['surnom'] password = formConnex.cleaned_data['passeword'] formConnex = ConnexionForm() dicInfoCon = { 'surnom_key':email, 'password_key':password, 'envoi_key':envoi } return render(request,'accueil/index.html',dicInfoCon) else: envoi = False formConnex = ConnexionForm() return render(request,'accueil/index.html','formConnex_Key':formConnex}) -
Program works when I run it on the IDE (Pycharm) but not when I run it on the terminal?
So I've written a desktop application on Python. It works fine when I run it by manually clicking 'Run main' through the IDE but when I do: python main.py the terminal does find the program but doesn't recognize the libaries. I've tried installing the libaries/modules a couple of times on the terminal and it says i've installed them but i guess not. These are the libaries/modules that refuses to work. from iconsdk.icon_service import IconService from iconsdk.providers.http_provider import HTTPProvider The output on the console (when I run 'python main.py') is this: Traceback (most recent call last): File "main.py", line 1, in import gui File "/Users/adam/PycharmProjects/igotmemed/gui.py", line 9, in import blockgen File "/Users/adam/PycharmProjects/igotmemed/blockgen.py", line 2, in from iconsdk.providers.http_provider import HTTPProvider File "/Users/adam/miniconda3/lib/python3.7/site-packages/iconsdk/providers/http_provider.py", line 17, in import requests File "/Users/adam/miniconda3/lib/python3.7/site-packages/requests/init.py", line 43, in import urllib3 File "/Users/adam/miniconda3/lib/python3.7/site-packages/urllib3/init.py", line 8, in from .connectionpool import ( File "/Users/adam/miniconda3/lib/python3.7/site-packages/urllib3/connectionpool.py", line 26, in from .packages.ssl_match_hostname import CertificateError ImportError: cannot import name 'CertificateError' from 'urllib3.packages.ssl_match_hostname' (unknown location) Something significant to note is 'CertificateError'. -
Django force migrations/database syncing
I had my migrations file in version control, and it went out of sync between production and development (I know, that was the mistake, but it's happened now). As a result, I couldn't run migrations in production. I deleted the migrations folder, and then re-ran makemigrations and migrate. makemigrations logs out creating all the fields. However, migrate simply says "no migrations to apply", and the extra fields do not appear in the database. All I've changed is adding nullable fields to a model, so it should be a straightforward migration. I can drop the whole db and start over, but I'd prefer not to because it takes a long time to re-populate. Is there a way that I can force Django to find the differences between the DB and the models, and build the correct migrations to add the fields? I attempted adding nonsense models to try and trigger a refresh. But that hasn't changed anything. -
Convert Image File Object to File Object in angular 6
i'm getting image object with url address which by calling angular httpClient.get(). I stuck here about to convert image object to file object -
Template tag for going from model1 to model2 that has foreign key to that model1
Is there a template tag or a way that I can go from my main model to a specific model that has a foreign key to my main model? models.py class BillingAddress(models.Model): user = models.ForeignKey(UserCart, on_delete=models.CASCADE) address1 = models.CharField(max_length=120, null=True) class HomeAddress(models.Model): user = models.ForeignKey(UserCart, on_delete=models.CASCADE) address1 = models.CharField(max_length=120, null=True) class UserCart(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, default=None) I want to get the 'address1' field from the BillingAddress that is related to a usercart. I don't think that I can use {{usercart.address1}} as both HomeAddress and BillingAddress have a field called address1 and are related to the usercart. Thanks! -
How to track requests in Django with an ID integer?
I develop an Django application in which when the user makes a POST, it creates some .txt files in the server. All txt files that are created in a request, have the same ID integer in their name in order to differentiate among the requests. For example: with the first POST --> 1_file.txt with the second POST --> 2_file.txt To succeed that every function in my server code (views.py or utils.py) that creates a txt file have a function_name.counter variable to keep track the times that each function runs (by the users' POSTs): def getEmail(email): getEmail.counter += 1 with open(BASE_DIR + str(getEmail.counter) + "_Email.txt", "w") as f: f.write('%s' % email) getEmail.counter = 0 But that way is such an error prone and with the apache's restart all .counter change to zero. Is there a more efficient way to succeed that ? -
How to fix "undefined" JSON response sent from Python to Javascript
I'm writing a web app for my personal website using "Django". The app is a "python script" that responds to a "javascript script" with JSON data, but I get "SyntaxError: JSON.parse: unexpected character at line 1 column 1 of the JSON data". I have no errors in the code. I tried the following answers: how to fix undefined data from json data? JSON property returning undefined -The Python script: #!/bin/python3 from django.http import JsonResponse return JsonResponse({'foo':'bar'}) -The JAVASCRIPT: $.ajax({ type: "GET", url: '{% static 'location_json.py' %}', success: callbackFunc }); function callbackFunc(response) { // do something with the response console.log(response.foo); } Actual results are "undefined". Expected results is the word "bar". -
Django: migration inserts data into a wrong db (when running tests)
I have a rather simple migration that creates a table and then populates it with some initial data. Everything works fine when I run the migrations in 'normal' mode. However, when I run tests, the test runner creates a separate db for tests (say, test_my_default_db), this migration creates the tables in the test database, but the data is then written to the default db (my_default_db). The function that is run for inserting the data accepts schema_editor, but I couldn't find how to use it to run python database code as opposed to raw SQL. Here is a gist of the migration: def load_init_data(apps, schema_editor): MyModel = apps.get_model("my_app", "MyModel") items = [...] for item in items: MyModel.objects.create(**item) class Migration(migrations.Migration): dependencies = [...] operations = [ migrations.CreateModel(name='MyModel',...) migrations.RunPython(load_init_data, delete_init_data) ] How can I make sure that the data is written to the test database instead of the default database? -
How can I use rest_framework.authtoken without create table authtoken_token in Django
When I added rest_framework.authtoken and used Token.objects.get_or_create(user = user) for check auth call API, django request must create table authtoken_token in DB, but customer don't want add new table in DB. So, have any way resolve it? Thanks for your time!!!