Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Integrity error when creating a user in django
I want my admin to be able to login and create users on my Django app, but each time I try to create a user I get this error message IntegrityError at /backoffice/add-exco/ (1062, "Duplicate entry '1' for key 'user_id'") The approach I used was to extend the User model using a one-to-one link. I also saw a post on stackoverflow suggesting how to solve this by doing the following Change your OneToOneField to a ForeignKey In your form validation make sure that a record does not exist When creating the form check if an entry already exists and then allow the user to edit it. I do not know how to go abt 2, 3 is there a better approach? Below is my code on models.py class AdditionalProfile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, null=True) mobile1 = models.CharField(max_length=15) mobile2 = models.CharField(max_length=15, blank=True, null=True) occupation = models.CharField(max_length=5, choices=OCCUPATION_FIELD, default=CHOOSE) job_cader = models.CharField(max_length=5, choices=JOB_CADER, default=CHOOSE_JOB) profile = models.ImageField(blank=True, null=True, upload_to='backend/') def __str__(self): return self.user.username on forms.py class RegisterForm(UserCreationForm): class Meta(): model = User fields = ('username', 'first_name', 'last_name', 'email', 'password1', 'password2') def save(self, commit=True): user = super().save(commit=False) user.username = self.cleaned_data['username'] user.first_name = self.cleaned_data['first_name'] user.last_name = self.cleaned_data['last_name'] user.email = self.cleaned_data['email'] if commit: user.save() return … -
Automatically create a token for admin in Django
I am looking for a method to create, automatically, a token with rest_framework.authtoken.models.Token when admin logins into admin panel. I can set-up it manually by adding the Token, but I would prefer to have it automatically created at login and destroyed at logout. -
django rest framework token authorization
I'm doing tutorial and I have a problem with access to data with authorization token. I changed in my settings.py REST_FRAMEWORK = { 'DEFAULT_PERMISSION_CLASSES': ( 'rest_framework.permissions.IsAuthenticated', ), I generate users and tokens for them, if I try GET, response is {"detail":"Authentication credentials were not provided."}curl: (6) Could not resolve host: Token curl: (6) Could not resolve host: e7e9047a515b141209ace33597b53771ef8f5483' i used commad: curl -X GET http://127.0.0.1:8000/api/example/ -H 'Authorization: Token 9944b09199c62bcf9418ad846dd0e4bbdfc6ee4b' from https://riptutorial.com/django-rest-framework/example/28222/using-curl of course with my token and address If I change 'rest_framework.permissions.IsAuthenticated' to 'rest_framework.permissions.AllowAny' and use curl -X GET http://127.0.0.1:8000/api/v1/friends/there are no problems, I'm getting json form database. I don't know what i'm doing wrong :( -
How to change a label of AuthenticationForm called in the LoginView and how to use another form in LoginView ? (Django 3.0)
I'm learning Django 3.0 and I'm actually using the django.contrib.auth.views.LoginView Here is my views.py file: from django.contrib.auth.views import LoginView class CustomLoginView(LoginView): template_name = "blog/loginview.html" And here is my urls.py file: from django.contrib.auth.views import LoginView from django.conf.urls import url urlpattenrs = [ url(r'^login/$', views.CustomLoginView.as_view(), name='login') ] I know I could put everything in the url without making my own view but I wanted to test it. Here is my template: <h1>Connection with LoginView</h1> <form method="POST" action="."> {% csrf_token %} {{ form.as_p }} <input type="hidden" name="next" value="{{ next }}" /> <input type="submit" value="Connect" /> </form> Everything works perfectly, but on my page, I can see the default labels from the AuthenticationForm used by default by the LoginView. These are Username: and Password:. Now here are my questions: Is it possible to change the labels to foo instead of Username: and bar instead of Password: from the template and keep the {{ form.as_p }} in the template? Or even better, changing the labels from the CustomLoginView ? Is it possible to use a custom form for the CustomLoginView ? Or even better, directly in the LoginView ? Thank you for your help. -
Django - map an argument to model
I'm sorry if this is a noob question. I'm new to this and even though I believe it is a simple problem I can't seem to find the right terms for googling. I have a several types of devices. Since they have notably different characteristics, I cannot accommodate them into one model. So I have separate models for each device type. I also have a table (model) of device types, i.e. a simple table which lists all available types. Each device a memeber called device type which is a foreign key to this table. Minimal example: from django.db import models class DeviceType(models.Model): device_type = models.CharField(max_length=30) class Foo(models.Model): memeber_a = models.CharField(max_length=30) memeber_b = models.CharField(max_length=30) device_type = models.ForeignKey(DeviceType, on_delete=models.PROTECT) class Bar(models.Model): memeber_a = models.URLField() memeber_b = models.URLField() memeber_c = models.CharField(max_length=30) device_type = models.ForeignKey(DeviceType, on_delete=models.PROTECT) I also added a simple view which lists all available types by querying the DeviceType model. Now I wish that upon clicking on each type (they are links), a page would open, listing all devices of this type. It is a simple matter to send the correct DeviceType.id within the view I have. However, new I have a view which receives the id as an argument, and needs … -
How to use post_save and use instance.save inside post_save without call post_save signal again?
I'm using a signal to change the uploaded file and do some process to convert the .mkv|mp4 file into .m3u8 and .ts files, but when i save the instance using new .m3u8 file created in the signal, the instance.save method call the signal again, and this raise a error. Code example: @receiver(post_save, sender=Lecture) def handle_video_upload(sender, instance, created, **kwargs): # check if a new video has uploaded file_has_changed = instance.tracker.has_changed('file') if created or file_has_changed and instance.file_type == "V": # .../ process to convert video into a .m3u8 file... # open the m3u8 created file and change the original (mp4, mkv...) file for the m3u8 with open(m3u8_absolute_path, "r") as file_object: file_m3u8 = File(name=m3u8_absolute_path, file=file_object) instance.file.save(m3u8_filename, file_m3u8) # this call this signal again and raise a error the file field is: file = models.FileField() -
Pass instance field to function as parameter
I have this code which generates slug for django models. I have a different model field which is passed to function for generating it from (for example- name, title) I marked variable name by naming it HELP_HERE_INSTANCE_FIELD_PASS_TO_FUNCTION How do I pass this "title", "name" fields that so this function will work for any field name I pass it to. # utils.py DONT_USE = ['create'] def random_string_generator( size=2, chars=string.ascii_lowercase + string.digits ): return ''.join(random.choice(chars) for _ in range(size)) def unique_slug_generator(instance, HELP_HERE_INSTANCE_FIELD_PASS_TO_FUNCTION, new_slug=None): if new_slug is not None: slug = new_slug else: slug = slugify(instance.HELP_HERE_INSTANCE_FIELD_PASS_TO_FUNCTION) Klass = instance.__class__ qs_exists = Klass.objects.filter(slug=slug).exists() if qs_exists: new_slug = f"{slug}-{random_string_generator(size=4)}" return unique_slug_generator(instance, HELP_HERE_INSTANCE_FIELD_PASS_TO_FUNCTION, new_slug=new_slug) return slug I will use that function here # models.py class Category(models.Model): name = models.CharField(max_length=64) slug = models.SlugField(unique=True, blank=True) class Event(models.Model): title = models.CharField(max_length=128) slug = models.SlugField(unique=True, blank=True) def event_slug_pre_save_receiver(sender, instance, *args, **kwargs): if not instance.slug: instance.slug = unique_slug_generator( instance, HELP_HERE_INSTANCE_FIELD_PASS_TO_FUNCTION="title" ) def category_slug_pre_save_receiver(sender, instance, *args, **kwargs): if not instance.slug: instance.slug = unique_slug_generator( instance, HELP_HERE_INSTANCE_FIELD_PASS_TO_FUNCTION="name" ) -
Word or pdf file from own website to csv file
I want to save a word or pdf file in csv to my database in django. I have searched for youtube videos but couldn't find any. Please help -
How to upload django website (basic HTML) onto Heroku without using Git/GitHub AT ALL?
Is this possible? I've read other threads but they do not answer the question and are deprecated besides. I have made my django project's website in PyCharm and I want to now host it on Heroku so I can give people a hyperlink to go to a basic HTML website instead of http://127.0.0.1:8000/ (which will eventually host my app which is already built). Any help would be appreciated. Ideally I would like a step-by-step SIMPLE guide for porting pycharm django html code into heroku or some other easier hosting website if some such hosting service exists. -
Hello, I'm trying to install channels but it's not installing because It is finding it hard to install twisted, what can I do?
I'm trying to install channels but it's not installing because It is finding it hard to install twisted, what can I do? it brings this error and stops. How can I go about this? copying src\twisted\internet\test\fake_CAs\chain.pem -> build\lib.win-amd64-3.8\twisted\internet\test\fake_CAs copying src\twisted\internet\test\fake_CAs\not-a-certificate -> build\lib.win-amd64-3.8\twisted\internet\test\fake_CAs copying src\twisted\internet\test\fake_CAs\thing1.pem -> build\lib.win-amd64-3.8\twisted\internet\test\fake_CAs copying src\twisted\internet\test\fake_CAs\thing2-duplicate.pem -> build\lib.win-amd64-3.8\twisted\internet\test\fake_CAs copying src\twisted\internet\test\fake_CAs\thing2.pem -> build\lib.win-amd64-3.8\twisted\internet\test\fake_CAs copying src\twisted\mail\test\rfc822.message -> build\lib.win-amd64-3.8\twisted\mail\test copying src\twisted\python\test\_deprecatetests.py.3only -> build\lib.win-amd64-3.8\twisted\python\test copying src\twisted\trial\test\_assertiontests.py.3only -> build\lib.win-amd64-3.8\twisted\trial\test copying src\twisted\words\im\instancemessenger.glade -> build\lib.win-amd64-3.8\twisted\words\im copying src\twisted\words\xish\xpathparser.g -> build\lib.win-amd64-3.8\twisted\words\xish running build_ext building 'twisted.test.raiser' extension error: Microsoft Visual C++ 14.0 is required. Get it with "Build Tools for Visual Studio": https://visualstudio.microsoft.com/downloads/ ---------------------------------------- ERROR: Command errored out with exit status 1: 'C:\Users\sirto\Anaconda3\envs\feb2020\python.exe' -u -c 'import sys, setuptools, tokenize; sys.argv[0] = '"'"'C:\\Users\\sirto\\AppData\\Local\\Temp\\pip-install-jb1hixq_\\twisted\\setup.py'"'"'; __file__='"'"'C:\\Users\\sirto\\AppData\\Local\\Temp\\pip-install-jb1hixq_\\twisted\\setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(__file__);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' install --record 'C:\Users\sirto\AppData\Local\Temp\pip-record-bqr18jdh\install-record.txt' --single-version-externally-managed --compile --install-headers 'C:\Users\sirto\Anaconda3\envs\feb2020\Include\twisted' Check the logs for full command output.` -
Force model fields in Django
When creating model in Django for example something like this: class Musician(models.Model): first_name = models.CharField(max_length=50, primary_key = True) last_name = models.CharField(max_length=50) instrument = models.CharField(max_length=100) I noticed some problem (not sure if that's best word) with this approach. There is nothing preventing you from creating something like: musician = Musician() musician.save() effectively having primary_key value equal to None. I would like to force user to set first_name, but frankly speaking I cannot find any simple solution for that. Is there a way to achieve this? -
How to access jinja variables of dictionary which is rendered through ajax call in Django
t.html: {% load static %} <!DOCTYPE html> <html lang="en"> <head> <meta charset=\"utf-8"\> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous"> <title>Title</title> </head> <body> <form method="post"> <textarea id="t1" name="editor">{{c}}</textarea> <br> <button type="button" id="b1" onclick="calling();">press</button> </form> **{{c}}** **{{b}}** <script type="text/javascript"> function calling(){ $.ajax({ type:'POST', url: "{% url 'test' %}", data: { csrfmiddlewaretoken: '{{ csrf_token }}' }, success: function(){ alert("Hello"); }, error: function(){ alert("sorry"); } }); } </script> </body> <script src="https://code.jquery.com/jquery-3.4.1.slim.min.js" integrity="sha256-pasqAKBDmFT4eHoN2ndd6lN370kFiGUFyTiUHWhU7k8=" crossorigin="anonymous"></script> <script src="https://code.jquery.com/jquery-3.4.1.min.js" integrity="sha256-CSXorXvZcTkaix6Yvo6HppcZGetbYMGWSFlBw8HfCJo=" crossorigin="anonymous"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js" integrity="sha384-ApNbgh9B+Y1QKtv3Rn7W3mgPxhU9K/ScQsAP7hUibX39j7fakFPskvXusvfa0b4Q" crossorigin="anonymous"></script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js" integrity="sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl" crossorigin="anonymous"></script> </html> I want value in {{c}} after ajax call. tview.py: from django.shortcuts import render def home(request): return render(request, 't.html') def test_view(request): print("hello") c = 2+3 dict1 = {'c': c, 'b': 'hey'} return render(request, 't.html', dict1) urls.py: from django.conf.urls import url from . import tview urlpatterns = [ url(r'^$', tview.home), url(r'^test', tview.test_view, name='test') ] enter image description here And when i press button ajax call is successfully made and did show a dictionary content on a chrome developer tools at response preview but not showing in main front page. This is the image. -
django Many to Many fildes
i want to add in only one user from Available classic to Chosen classic but not from admin page from view when user click on button I tried this pro = Profile(user=request.user) pro.classic.add(name='Frank Sinatra-i love you baby') but i get tthis error -
AttributeError: Got AttributeError when attempting to get a value for field `name` on serializer `CitySerializers`
AttributeError: Got AttributeError when attempting to get a value for field name on serializer CitySerializers. -
What to choose Class Based Views or Function Based Views?
I really want know is that bad if someone know only one method from the above two ? i mean just working on something like class based views and not much in functions based views is a bad sign for getting hire in company. By the way i worked on both of them but i really like how quick class based views are and helps to avoid repeatation of code. Also, the best part in class based views i find is during testing. That's the biggest reason why i like class based views more. But seriously i dont know how knowing only one of the two can affect getting me hired or something. As i dont know what developers like to work on more. Love to know your opinions guys please suggest. -
hosting Django application on Apache
I'm following a tutorial on hosting Django application on Apache, and I'm new to these types of server error. I modified the apache config file to communicate with the wsgi of my application using the following code: LoadModule wsgi_module "c:/users/adwy/appdata/local/programs/python/python35/lib/site-packages/mod_wsgi/server/mod_wsgi.cp35-win_amd64.pyd" WSGIScriptAlias / "D:/Backup/Learning Python/Organized and important file/Learning files and sheets/Django_ Learning_ 1/weblog_app/weblog_app/wsgi.py" WSGIPythonHome "C:/Users/Adwy/AppData/Local/Programs/Python/Python35" WSGIPythonPath "D:/Backup/Learning Python/Organized and important file/Learning files and sheets/Django_ Learning_ 1/weblog_app/weblog_app" Alias /static/ C:/Users/Adwy/Adwy/Django_ Learning_ 1/Lib/site-packages/django/contrib/admin\static Alias /templates/ C:/Users/Adwy/Adwy/Django_ Learning_ 1/Lib/site-packages/django/contrib/admin/templates <Directory C:/Users/Adwy/Adwy/Django_ Learning_ 1/Lib/site-packages/django/contrib/admin/static> Require all granted </Directory> <Directory C:/Users/Adwy/Adwy/Django_ Learning_ 1/Lib/site-packages/django/contrib/admin/templates> Require all granted </Directory> <Directory "D:/Backup/Learning Python/Organized and important file/Learning files and sheets/Django_ Learning_ 1/weblog_app/weblog_app"> <Files wsgi.py> Require all granted </Files> </Directory> -- Now I restarted my apache server, and run the Django server in parallel, I get Error 500, here I copy below the logs of the Error from the Apache server: [Sat Apr 04 18:41:05.681919 2020] [wsgi:warn] [pid 8608:tid 288] (70008)Partial results are valid but processing is incomplete: mod_wsgi (pid=8608): Unable to stat Python home C:/Users/Adwy/AppData/Local/Programs/Python/Python35. Python interpreter may not be able to be initialized correctly. Verify the supplied path and access permissions for whole of the path. [Sat Apr 04 18:41:05.725921 2020] [mpm_winnt:notice] [pid 8608:tid 288] AH00354: Child: Starting 150 … -
Trying to implement a read more button that is specific to Django model attribute
So I've had success in creating a 'read more' that displays more information on a music artist and the button appears under each artist on my page. The button displays the bands bio which is taken from a Django model that holds the bio information in my database. The button works for the first artist on the page but when I click the button under the other artists on the page, it still only displays the bio for the first band (the one at the top of the page). How do I make it so that the button displays the information of each specific band? Here is my html code <p><span id="dots">...</span><span id="more">{{ artist.bio }}</span></p> <button onclick="myFunction()" id="readmore">Show more on this artist</button> Here is my css code p { font-size: 18px; margin-left: 40px; margin-right: 40px; } #readmore { font-size: 18px; color: darkgrey; margin-left: 40px; margin-right: 40px; } #more { display: none; } Here is my java function myFunction() { var dots = document.getElementById("dots"); var moreText = document.getElementById("more"); var btnText = document.getElementById("readmore"); if (dots.style.display === "none") { dots.style.display = "inline"; btnText.innerHTML = "Show more on this artist"; moreText.style.display = "none"; } else { dots.style.display = "none"; btnText.innerHTML = "Hide information on … -
Date Picker inside the Form is not showing up
forms.py Here in forms.py i have written the form perfectly but can't find the problem from bootstrap_datepicker_plus import DatePickerInput,DateTimePickerInput class SchedulAuctionForm(forms.ModelForm): # auction_start_date=forms.DateTimeField(widget=DateTimePickerInput()) # auction_end_date = forms.DateTimeField(widget=DateTimePickerInput()) class Meta(): fields=('auction_start_date','auction_end_date') model = models.CurrentAuction widgets = { 'auction_start_date': DateTimePickerInput(), 'auction_end_date': DateTimePickerInput(), } views.py class AuctionScheduling(UpdateView): model = models.CurrentAuction template_name = 'auctions/admin/auction_scheduler.html' form_class = forms.SchedulAuctionForm success_url = reverse_lazy('home') def form_valid(self, form): prop = get_object_or_404(models.PropertyReg,pk=self.kwargs.get('pk')) prop = form.cleaned_data['something'] prop.save() return super().form_valid(form) auction_scheduler.html {%extends 'auctions/admin/admin_base.html'%} {%load static%} {%load bootstrap4%} {% bootstrap_css %} {% bootstrap_javascript jquery='full' %} {% include "bootstrap_datepicker_plus/input.html" %} {%block heading%} <br/> <br/> <br/> <center><h1 id="scroll">Auction Schedule</h1></center> <br/> {%endblock%} {%block content%} {{ form.media }} <br/> <div class="container"> <form method="post"> {%csrf_token%} {%bootstrap_form form%} <input type="submit" value="Schedule This" class="btn btn-danger"> </form> </div> <br/> {%endblock%} enter image description here As You can see in the image picker is not showing up at all -
How can i train model and then use in my django project to classify text getting from scrapper?
I am making a web scrapper which scrap news from url save into database after classification. Im using django and python for web and mongoDB as an database. -
Django serializer with a filed that has a OneToOne relationship
In my project I have two 'types' of users: Customers and Businesses. They are an extension of the django base User from django.contrib.auth.models.User. I have in my models.py: class Customer(models.Model): user = models.OneToOneField(User, related_name='user', on_delete=models.CASCADE) birth_date = models.DateField(blank=True, null=True) phone = PhoneNumberField(unique=True) def __str__(self): return self.user.username class Business(models.Model): user = models.OneToOneField(User, related_name='business', on_delete=models.CASCADE) cf = models.CharField(max_length=16, validators=[ssn_validation]) birth_date = models.DateField(null=True) city = models.CharField(max_length=50, blank=False) address = models.CharField(max_length=150, blank=False) Ok, then I have two different registration, one for Customers and one for Businesses. A problem is that, to validate the password, sent from a REST API, I need to compare password with password2, create a User (django base), and pass it to my Customer.objects.create, like: I have in my serializers.py: class CustomerRegistationSerializer(serializers.ModelSerializer): username = serializers.CharField(source='user.username', validators=[UniqueValidator(queryset=User.objects.all())]) email = serializers.CharField(source='user.email', validators=[UniqueValidator(queryset=User.objects.all())]) first_name = serializers.CharField(source='user.first_name') last_name = serializers.CharField(source='user.last_name') password = serializers.CharField(source='user.password', write_only=True) password2 = serializers.CharField(style={'input_style': 'password'}, write_only=True) birth_date = serializers.CharField(required=False) class Meta: model = Customer fields = ['id', 'username', 'email', 'password', 'password2', 'first_name', 'last_name', 'birth_date', 'phone'] def save(self): username = self.validated_data['user']['username'] password = self.validated_data['user']['password'] password2 = self.validated_data['password2'] email = self.validated_data['user']['email'] first_name = self.validated_data['user']['first_name'] last_name = self.validated_data['user']['last_name'] phone = self.validated_data['phone'] try: birth_date = self.validated_data['birth_date'] except KeyError: birth_date = None if password != password2: raise … -
Django:Web browser based caching and Proxy server based caching
I'm new in Django. Actually i'm learning Django's cache framework and i'm so confused how actually caching system works in Django. As i written a simple view in Django and also cache it with Django's cache framework. from django.shortcuts import render,redirect from django.views.decorators.cache import cache_page @cache_page(60) def hi(request): res= render(request,'payment.html') return res Note:In settings.py cache is file-system based cache Does the cache of hi() view is browser based cache or proxy based cache?if it is proxy based cache then does here proxy server is my own computer or it is Virtual Machine?How i can work with both types of cache separately in Django? -
What is a good way to perform calculations in Django
I'm working on an app that recieves inputs from the user, performs calculations and returns the results. As far as I understand one can implement such functionality solely within models. But in my case I use instances of several different model classes to calculate intermediate variables or instances of other classes. Thus, this approach will require using model inheritance which can become very complicated for someone unexperianced like me. Another way is to keep all model classes separate and perform all intermediate calculations in views. I need to know if my understanding is correct and what is a good practice. Examples are welcome :-) -
Can I limit the dates possibilities using django widget DateInput, ex. between 2020-01-01 and 2023-12-31
Using the widget DateInput, I would like to limit the range of dates offered by the datepicker to a set range, for example between Jan. 1, 2020 to Dec. 31, 2023. I understand, that the date could be validated after it has been entered but is it possible to limit what the user could enter. -
Django Cassandra sync_cassandra not syncing models
I created an app named "Example" then copy and pasted example code given docs. App create code: python manage.py startapp Example in Example/models.py: import uuid from cassandra.cqlengine import columns from django_cassandra_engine.models import DjangoCassandraModel class ExampleModel(DjangoCassandraModel): example_id = columns.UUID(primary_key=True, default=uuid.uuid4) example_type = columns.Integer(index=True) created_at = columns.DateTime() description = columns.Text(required=False) when ı write this to console.. it only creates keyspace.. Not syncing model.. python manage.py sync_cassandra Why it not syncing model to database? İt creates keyspace? -
Django fetch data from database in base.html
I have a navbar in my base.html file. The navbar has dropdown for recents and trending posts. The posts in the dropdowns are to be fetched from the database. I'm not sure if creating a view function for base.html is a good idea as I've never seen it before. I tried adding varaibles in block in the dropdowns in base.html but it got really repititve as I have to write variables in my every page. I was wondering if theres an efficient way to fetch data from the databse in my base.html file. Thanks!