Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Creating a user history API in Django
I am new to Django, I am using it to build a server where a person can create an account, then add online newspaper articles that they have viewed. I want the user to be able to view all of the articles they have viewed and I want ONLY that user to be able to see it. Now the database design has gotten my head pretty confused. My schema: User(id, username, password, email) Article(is, url, title, etc...) History(id, user_id, article_id, last_viewed) I know how to query for specific users history in the shell (History.objects.filter(User=some_user)), but I don't know how to give each user a history field which automatically queries and find their history. Also, do I have to have one big history table that all of the different user's histories are stored in or can I have a different history table per user? I just want each user to have a history of all of the articles that they have viewed. Any advice you can give? I have been using tasty pie to create the REST api. -
Django dynamic model
I'm trying to create budget app and struggling for creating dropdown lists (tables in database) based on each other in admin panel. I want to created a entry model in which you need to choose subcategory based on category. tried with pirmary keys for all of objects of category class but seems that it doesnt work. class Category(models.Model): # category category_type = models.CharField(max_length=150) def __str__(self): return self.category_type class Category_Types(models.Model): parent_category = models.ForeignKey(Category, on_delete='CASCADE') category_type = models.CharField(max_length=150) def __str__(self): return self.category_type class Entry(models.Model): # single entry to budget database entry_date = models.DateTimeField(auto_now_add=True) transaction_date = models.DateField() try: for category in Category.objects.all(): category_type = models.ForeignKey(category,on_delete='CASCADE') except: pass I doesn't show me any possibilities for adding Entry in admin panel -
Dynamic parameter of url django template
Inside an html page I have two radio buttons with values A and B. I also have an url to a view that needs two parameters, one is a parameter that I can easily access through the django context variable but the second parameter should have the value A or B based on which radio button is checked. I don't know how to get this done. I've red this post: Get javascript variable's value in Django url template tag which is kinda what I'm looking for but I don't understand how can this be implemented in my case. Also checked this post: https://www.reddit.com/r/django/comments/39q9lm/url_tag_in_template_with_a_dynamic_parameter/ which is pretty much the same concept. What I tried to do in my template is: <option value="{% url 'view' tmp i %}".replace(/tmp/, 'A');> </option> which is not exactly what I'm aiming for but it was just to check if this is working.. This is not working to me though. Of course my goal is not to replace tmp with 'A' but with 'A' or 'B' based on which radio button is checked by the user inside my html page. Radio buttons have ids radio1, radio2. I could use javascript of course but I'd like to stay … -
Create nested object (1-1 relationship) from flattened POST request
I'm trying to implement two serializer classes which will allow me to create both user and profile objects from a flattened POST request. I tried the implementation described here and it works perfectly fine for updating (and only updating) existing objects. Here is my current implementation: # serializers.py class UserSerializer(serializers.ModelSerializer): password = serializers.CharField( write_only=True, required=True, style={"input_type": "password"} ) class Meta: model = User fields = ( "username", "password", # ... "date_joined", ) read_only_fields = ("date_joined") class UserProfileSerializer(serializers.ModelSerializer): user = UserSerializer() def to_representation(self, instance): representation = super().to_representation(instance) representation.update(representation.pop("user")) return representation def to_internal_value(self, data): user_internal = {} for key in UserSerializer.Meta.fields: if key in data: user_internal[key] = data.pop(key) internal = super().to_internal_value(data) internal["user"] = user_internal return internal def create(self, validated_data): user_data = validated_data.pop("user") user = User.objects.create(**user_data) user.set_password(user_data["password"]) user.save() profile = UserProfile.objects.create(user=user, **validated_data) return profile class Meta: model = UserProfile fields = ( "user", "date_updated", # ... "phone_number", ) # views.py class Register(generics.CreateAPIView): serializer_class = UserProfileSerializer name = "userprofile-create" I expect the app to take the flattened JSON and create both user and profile objects. Example POST body: { "username": "test_user", "password": "P@$$w0rd", "first_name": "Foo", "last_name": "Boo", "email": "foo@example.com", "street": "Random Street", "street_number": "11", "flat_number": "11", "zip_code": "11-111", "city": "Some City", "province": 1, "phone_number": … -
How can I get screenshot of an html container, using django?
Consider we have a simple div container inside an html page which has lots of other stuff too. I am seeking to design a button for users, so when clicked, it returns the screenshot image of only that particular container. I am currently working inside a django project and wondered maybe there is a pure html or java solution to this without using python. However in my searches I haven't found anything on python that can help me on this either. For example the div looks something like this: <div class="row" style="height:1200px; overflow-x: hidden;" id="The_chart_that_we_want_its_screenshot"></div> The id is triggered by a java code later in the html script which loads a chart based on some data (which is constantly changing) from database. And since every time the user opens that html page, a different chart is shown in that container, this button is needed for the sake of user's reporting needs. -
Query django foreignkey relationship
I am developing an audit management information system where I can record all finding related to an audit. I have models with foreignkeys relationship. How do I see all findings with a particular assignment and audit_title and unit? See relevant codes below. model.py content class Unit(models.Model): unit_name = models.CharField(max_length=30, blank=True, null=True) def __unicode__(self): return self.unit_name class Assignment(models.Model): assignment_name = models.CharField(max_length=30, blank=True, null=True) def __unicode__(self): return self.assignment_name class Task(models.Model): task_title = models.CharField(max_length=35, blank=True, null=True) return self.task_title class Finding(models.Model): assignment = models.ForeignKey(Assignment, blank=True, null=True) audit_title = models.ForeignKey(Task, blank=True, null=True) auditor = models.ManyToManyField(User, blank=True) unit = models.ForeignKey(Unit, blank=True, null=True) audit_period = models.DateField(auto_now_add=False, auto_now=False, blank=True, null=True) contact_person = models.CharField('Contact Person', max_length=500, blank=True, null=True) finding = models.TextField('Detail Finding', max_length=500, blank=True, null=True) form.py class FindingSearchForm(forms.ModelForm): class Meta: model = Finding fields = ['assignment', 'audit_title', 'unit', ] -
DateTime range in django rest framework
I am creating an api which returns weather data of particular city for n number of days given.(api definition: weatherdata/city_name/ndays/).I have problem sorting out data for ndays. I sorted out the city name using simple icontains. similarly I want to sort out for ndays. previous ndays data needs to be shown. example: suppose today is 2019-08-29, on providing ndays to be 6, weather data of particular city has to be provided from 2019-08-24 to 2019-08-26. views.py class weatherDetail(APIView): def get_object(self, city_name, ndays): try: x = weatherdata.objects.filter(city_name__icontains=city_name) now = datetime.datetime.now() fromdate = now - timedelta(days=ndays) y = return x except Snippet.DoesNotExist: raise Http404 def get(self,*args,**kwargs): city_name = kwargs['city_name'] snippet = self.get_object(city_name,ndays) serializer = weatherdataserializer(snippet,many =True) return Response(serializer.data) models.py class weatherdata(models.Model): city_name = models.CharField(max_length = 80) city_id = models.IntegerField(default=0) latitude = models.FloatField(null=True , blank=True) longitude = models.FloatField(null=True , blank=True) dt_txt = models.DateTimeField() temp = models.FloatField(null = False) temp_min = models.FloatField(null = False) temp_max = models.FloatField(null = False) pressure = models.FloatField(null = False) sea_level = models.FloatField(null = False) grnd_level = models.FloatField(null = False) humidity = models.FloatField(null = False) main = models.CharField(max_length=200) description = models.CharField(max_length=30) clouds = models.IntegerField(null=False) wind_speed = models.FloatField(null = False) wind_degree = models.FloatField(null = False) urls.py urlpatterns = [ path('admin/', admin.site.urls), … -
Issue with getting argument value form django rest framework url
I have a django project that has an API view. The api view is associated with a url that accepts an argument in the url and a parameter after the ? in the parameters. I am trying to grab the argument that is located within the url which is widget_id to use it as a filter. I am running into an error. view: def put(self, request, pk, format=None): widget_id = self.kwargs.get('widget_id') user_id = self.request.query_params.get('user_id') user_widget = PersonWidgetDefinition.objects.all()\ .filter(widget_definition_id=widget_id, person_id=user_id).count() if user_widget == 0: serializer = PersonWidgetDefinitionSerializer(data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) if user_widget == 1: request.data.user_widget = True serializer = PersonWidgetDefinitionSerializer(data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=status.HTTP_202_ACCEPTED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) url: path('widgets/<int:widget_id>/user/', UserWidgetView.as_view(), name='user-widget'), error: TypeError at /api/v2/widgets/1/user/ put() got an unexpected keyword argument 'widget_id' -
Django DRF - how to deserialize an instance that requires a foreign key?
I have a Page model, and a Paragraph model that references its Page. I want to create both modules by deserializing a JSON representation like this: { "page": { "number": 32, "book": "Moby Dick", "paragraphs": [ { "label": "I am a Paragraph within the Page" } ] } } And here are my Paragraph and Page models: class Paragraph(models.Model): page = models.ForeignKey( Page, help_text="Every Paragraph must belong to a Page", related_name="paragraphs", on_delete=models.CASCADE, ) label = models.CharField(max_length=128) class Meta: db_table = 'my_paragraph' class Page(models.Model): # This is not unique! number = models.IntegerField() # This is not unique! book = models.CharField(max_length=128) # but "number" and "book" together are unique. class Meta: db_table = 'my_page' How can I deserialize that representation to instantiate my models? I tried creating these serializers below: class ParagraphSerializer (serializers.ModelSerializer): page = serializers.SlugRelatedField( slug_field="id", queryset=models.Page.objects.all(), ) class Meta: model = models.Paragraph fields = '__all__' class PageSerializer (serializers.ModelSerializer): paragraphs = ParagraphSerializer( many=True, ) # This method never gets called, because PageSerializer validation fails. def create(self, validated_data): paragraphs_data = validated_data.pop('paragraphs') page = models.Page.objects.create(**validated_data) for paragraph_data in paragraphs_data: # We'll need to find some way of adding a `page` field to this paragraph... paragraph_data['page'] = page.id serializer = ParagraphSerializer(data=paragraph_data) serializer.is_valid() serializer.save() class … -
How can load models image with django in css
I'm working on my blog website I want use my post's image in my post page for example my post list has some posts and when the user click in my post card Navigate to post page and this page i want show the post image in the background I know what can do for load image in html I know use /static/img/.../ But I want load image in css like this Background-image : url('') I tried this code but don't work : background-image: url('{{ MEDIA_URL }}/post_image/{{ post.image_url }}'); You know what can i do for this paye attention I import my image from my media folder -
Django session cookie marked as "third party" and blocked by Firefox
When I log in to my Django-based server using Firefox, the cookie passed to the browser gets marked as "Third Party" and thus gets blocked by default, with no option offered to create an exception, even though the cookie shows as being from "https://servername" which is identical to the URL. I found that if I access the server as "https://servername.domain.lol" instead of directly as "https://servername", the cookie gets marked correctly as first-party. I really don't want to force all users to use the FQDN instead of just the server name. Is there some way in Django or in my Nginx reverse proxy to set some header or something such that the browser will recognize that the cookie belongs to this site? -
Django-ratelimit not working in development mode
I am using django-ratelimit package. Everything is working fine and no error but it is not rate limiting my views. -
How to get extra JSON data during a POST request
My goal is to receive a JSON with all the information necessary to create a user, along with something extra that I'll use to create another object all in one go, using the recently created user and the additional information sent through the JSON. For context, my JSON currently looks like this: { "first_name": "John", "last_name": "Doe", "username": "newuser", "email": "johndoe@hotmail.com", "password": "somepassword", "profile_image": null, "type": 2 } type is the information not necessary for the creation of the user. My custom create function is looking like this, currently: def create(self, validated_data): new_user = User.objects.create_user(**validated_data) types = self.request.data.get("type") create_user_type = UserType.objects.create(user=new_user, type=types) return create_user_type It suffered a lot of changes after looking into the Django Rest Framework documentation, stackoverflow questions, and debugging. If I run the code the way it is now, This is what I get: AttributeError at /user/ 'UserSerializer' object has no attribute 'request' So I assume this happens because you can't get request through doing self.request. I tried placing this create in the viewset because I realized things worked slightly different there, but then this happens: TypeError at /user/ create_user() argument after ** must be a mapping, not Request I can edit my question to add any … -
How do you translate the slug value of a page?
I'm trying to implement a language switcher, for which I'm using the Django recommended form: <form action="{% url 'set_language' %}" method="post">{% csrf_token %} {% get_current_language as LANGUAGE_CODE %} <input name="next" type="hidden" value="{{ redirect_to }}"> <input name="language" type="hidden" value="{% if LANGUAGE_CODE == 'en' %}es{% else %}en{% endif %}"> </form> My urls.py is set up like so: urlpatterns = [ # Wagtail urls re_path(r'^cms/', include(wagtailadmin_urls)), re_path(r'^documents/', include(wagtaildocs_urls)), # Django urls path('admin/', admin.site.urls), path('i18n/', include('django.conf.urls.i18n')), ] urlpatterns += i18n_patterns( path(r'', include(wagtail_urls)) ) When I click to change my language, I am correctly forwarded to /en/slug or es/slug, depending on the language I have selected. However the actual slug value is not being translated. Since I have Spanish slugs for the Spanish pages, I am getting a 404 when I switch languages, because I am directed to the English slug value paired with the Spanish locale prefix (es). I also tried using the slugurl_trans template tag, but that didn't seem to work (maybe because I'm not explicitly defining any URLs in my i18n_patterns call?). Any guidance on this would be really helpful, as I've spent way too many hours on this! -
Django 2.2.4 - “No migrations to apply” when run migrate after makemigrations
I am trying to do a migration in django 2.2.4 in python 3.7. First I try to make do makemigations: python3 manage.py makemigrations I get: Migrations for 'main': main/migrations/0001_initial.py - Create model TutorialCategory - Create model TutorialSeries - Create model Tutorial But then I try the second step: python3 manage.py migrate I get: Operations to perform: Apply all migrations: admin, auth, contenttypes, main, sessions Running migrations: No migrations to apply. Even though a migration should happen. I tried deleting my migrations folder and then remaking it (with the empty __init__.py file inside) but it still doesn't work. (Note: I have been following along the tutorial: Linking models with Foreign Keys - Django Web Development with Python p.9 by sentdex) -
django-ratelimit not rate limiting my signup view
Everything is working but it is not rate limiting. @ratelimit(key='ip', rate='5/m') def signup(request) No error just not rate limiting. Development mode. Windows. Cache setting is django default cache Any example program how to use Django-ratelimit. -
How to implement authentication against a model which inherits AbstractBaseUser in Django?
I want to develop an endpoint that accepts user's data and stores it in databases. I want to develop another endpoint that accepts phone_number and password and if the user is authenticated it will return a token for the user. So I created a model named Person that inherits AbstractBaseUser in order to use phone_number not username for authentication. and I created a function that use django.contrib.auth.authenticate method to authenticate user. the problem is the method authenticate() always returns None for any user even if the user is in the database. I tried to build a custom authenticate method but the problem is still existing. -
first and last value is not displaying in chart.js used with django
i want to display the employee and salary in a graph, i used chart.js and django. but i cannot display the salary of first and last employee..any suggestion is appreciated. #views if request.method=="GET": return render(request, 'upload_pandas.html') else: file=request.FILES['myfile'] file_read=pd.read_excel(file) column_selection=file_read['Salary'] salary=[] salary=list(column_selection) print(salary) name=[] name=list(file_read['First Name']) print(name) lis=[salary,name] data={ 'salary_data': salary, 'label_data': name, } return render(request,'map.html',{'data':data}) #url.py urlpatterns=[ path('upload/',views.view_panda), ] the problem is here, when i print in console it prints all the value but it was not loading in the graph.enter image description here #map.html <html> <head> <title>Chart.js</title> </head> <body> <div > <div> <canvas id="genderchart" width="1000"></canvas> </div> </div> <scriptsrc="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.8.0/Chart.bundle.min.js"></script> <script> var label={% autoescape off %} "{{ data.salary_data }}" {% endautoescape %}; var label1={% autoescape off %} "{{ data.label_data }}" {% endautoescape %}; var lab=label1.split(',') console.log(lab) console.log(label) console.log(label1) new Chart(document.getElementById("genderchart"),{ type:'bar', data:{ labels:label1.split(','), datasets:[ { label:"employee", backgroundColor:"rgba(62,149,205,1)", borderColor: "rgba(62,149,205,1)", pointBackgroundColor:"rgba(62,149,205,1)", data: label.split(','), }, ] }, options:{ legend:{ labels:{ fontSize:18 } }, title:{ display : true, text : "Salary Wise", fontSize : 22.0 }, scales:{ yAxes:[{ offset: true, ticks:{ suggestedMin: true, fontSize:15.0, }, scaleLabel: { display:true, labelString:'Salary', fontSize:20.0, } }], xAxes:[{ desplay: true, offset: true, ticks:{ beginAtZero: true, fontSize:15.0, }, scaleLabel: { display:true, labelString:'Employee', fontSize:20.0, } }] }, responsive: … -
No changes in the Admin or the Api although Migrations are done successfully
I have pushed a Django project to a droplet and migrated my app. Migrations were done successfully. Then, I created a user and all the models appeared in the Admin. Later, I added a property to one of my models locally, then pushed the changes and pulled them on the server. Finally, I made migrations again, but this time the added property, although the changes were migrated successfully, did not appear in the admin or the API. I restarted the server many times, but that did not help. That's what I got when I ran the following two commands. command: python manage.py makemigrations Migrations for 'courses': courses/migrations/0002_exam_course_name.py - Add field course_name to exam command: python manage.py migrate Operations to perform: Apply all migrations: admin, auth, contenttypes, courses, sessions Running migrations: Applying courses.0002_exam_course_name... OK -
Previous solution for Django-MySQL collation no longer works
Have been using Django 2.x and MySQL 5.7 together for dozen of projects. Long ago had run across the problem of differing charsets/collations between different tables/columns triggering the "1215, 'Cannot add foreign key constraint'" IntegrityError. For at least a year or more, the problem was solved by adding the following to all my database definitions in settings.py: init_command": "SET character_set_connection=utf8mb4, collation_connection=utf8mb4_unicode_ci; All of the tables created and updated by Django through migrations after adding the init command were indeed set to utf8mbf_unicode_ci. (I went back and verified this today.) Now, out of nowhere: spent hours today troubleshooting a problem of failing migrations on an older project. Didn't originally look at the collation issue because nothing had been changed on either the database or in the Django connector. Lo and behold, all new tables are created as utf8mb4_general_ci, thus crashing as foreign keys tried to be written to existing _unicode_ci tables, despite no changes having been made to the init_command. I attempted to convert/rollback all affected tables using ALTER TABLE to convert to my desired collation, but any changes made by a migrations file implicitly converts again to _general_ci. I've looked back at my last few projects, and I see that … -
Extracting min and max value of Django model feature in template
I have a model like this: class Integer(models.Model): integer_value = models.IntegerField(default=0) current_price = models.DecimalField(max_digits=5, decimal_places=2, default=0.00) share = models.IntegerField(default=0) market = models.ForeignKey( IntegerMarket, on_delete=models.CASCADE, related_name='integers', default=None) def __str__(self): return str(self.integer_value) class Meta: ordering = ['integer_value'] In my template, for a given instance of IntegerMarket, I would like to extract the minimum and maximum values of integer_value, in order to then define the min and max value of an axis in JavaScript. For example, I might have an instance of IntegerMarket featuring five integers, with integer_value 1 through 5, respectively. I would then like to extract 1 as min and 5 as max. What's the most straightforward way to do this? -
Does form_valid() in django saves the ModelForm instance by default?
The official documentation says that form_valid() is called when valid form data is POSTed. And doesn't say anything about saving data. But I'm reading a book where it says that the default behavior of this method is saving the instance (for modelforms ) and redirecting user to success_url . So, I'm a bit confused. -
How to add a text delimiter correctly in Python
I want to export some data from DB to CSV file. I need to add a '|' delimiter to specific fields. At the moment when I export file, I use something like that: - To specific fields (at the end and beginning) I add '|': .... if response.value_display.startswith('|'): sheets[response.sheet.session][response.input.id] = response.value_display else: sheets[response.sheet.session][response.input.id] = '|'+response.value_display+'|' .... And I have CSV writer function settings like that: self.writer = csv.writer(self.queue, dialect=dialect, lineterminator='\n', quotechar='', quoting=csv.QUOTE_NONE, escapechar=' ', ** kwargs) Now It works, but when I have DateTime fields(where is space) writer adds some extra space. When I have default settings (sometimes) at the end and beginning CSV writer add double-quotes but I don't know why and what it depends on. -
How to reverse path for custom user when testing Django Rest Framework
I'm building a Django 3 app using a Custom User. I'm trying to test the Custom User, but I can't get the url using reverse. I'm using Django Rest Framework. myapp.api.urls.py: app_name = 'myApp' from django.urls import include, path, re_path urlpatterns = [ ... path('users/', include('users.urls'), name='UsersURLS'), ] myapp.users.urls.py from django.urls import include, path from . import api app_name = 'users' # namespace for reverse urlpatterns = [ path('', api.UserListView.as_view(), name='UsersPath'), ] myapp.users.api.py class UserListView(generics.ListCreateAPIView): queryset = models.CustomUser.objects.all() serializer_class = serializers.UserSerializer authentication_classes = (TokenAuthentication,) And in test_users_api.py: from users.api import UserListView user_detail_url = reverse('myApp:UsersURLS-list') ... def test_user_detail(self): self.client.force_authenticate(user=self.user) response = self.client.post(user_detail_url, {'pk': self.user.id }, format='json') Whatever I try for the reverse, I get an error that is it not a valid view or function name reverse('myApp:UsersURLS-list') reverse('users:UsersPath-list') reverse(UserListView) I'd be grateful for any idea what I'm doing wrong, and how to get the reverse URL. I have it working for the rest of my endpoints which use router, but I can't see what's needed for my Custom User, which I set up following a tutorial and it works fine otherwise. -
Want to fetch data from website and update in my django's sqlite database
I'm trying to fetch json data from a website and update my sqlite database in Django to show on the localhost. I am really stuck here. Please help me and could you please suggest me any website to take help? Thank you