Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
My comment system in Django is not working as expected
I'm creating an application where a user can create their own posts, and other users can comment on the posts. I have already tried retrieving comments from the database, and displaying them for that certain post, however this has been unsuccessful Here is my code to tackle this problem: views.py def comment(request, pk): form = CommentForm() comments = Comment.objects.filter(post=pk) if request.method == 'POST': form = CommentForm(request.POST) if form.is_valid(): comment = Comment() comment.body = form.cleaned_data['body'] comment.user = request.user comment.post = Post.objects.get(pk=pk) comment.save() return redirect('home') return render(request, 'posts/comments.html') else: return render(request, 'posts/comments.html', {'error': 'Please submit valid data'}) else: return render(request, 'posts/comments.html', {'form': form}, {'comments': comments}) comments.html {% block content %} <div class="container"> {% for com in comments.all %} <p>{{ com.body }}</p> <br> {% endfor %} {% if error %} {{ error }} <br> <br> {% endif %} <br> <br> <br> <br> <br> <form method="post"> <h2> Comment</h2> {% csrf_token %} {{ form.as_p }} <button type="submit" class="btn btn-primary"> Comment</button> </form> </div> {% endblock %} models.py class Comment(models.Model): body = models.CharField(max_length=130) user = models.ForeignKey(User, on_delete=models.CASCADE) post = models.ForeignKey(Post, on_delete=models.CASCADE) def __str__(self): return self.body This is expected to display a posts comments when a button is pressed to view the post, however the comments do not … -
What the best way to pass in a user-facing attribute and print it in html?
When my errors get caught by is_valid() in django, I print them in html. I'd like to add a friendly user-facing html title that prints along with the error so they know which form is invalid. I thought I could just add a custom attribute and print it, but the only attribute html can print is "name" for some reason. Django abstracts it away, but in this case the "name" attribute in the html object = end_date. I'd just like to print the "friendly" attribute but html prints nothing instead. Here is the form declaration: end_date = forms.DateField(widget=forms.TextInput(attrs={'id':"datepicker", 'autocomplete':"off", 'friendly':"End Date"}), required=True) Here is the un-abstracted html for this object that gets printed on the page error reload, you can see "End Date" right there, but it is still null on the page: <tr><th><label for="datepicker">End date:</label></th><td><ul class="errorlist"><li>This field is required.</li></ul><input autocomplete="off" friendly="End Date" id="datepicker" name="end_date" type="text" /></td></tr> The error printing. {% if form.errors %} {% for field in form %} {% for error in field.errors %} <div class="alert alert-danger"> <strong>{{ field.name }}: {{ error|escape }} </strong></strong> </div> {% endfor %} {% endfor %} {% for error in form.non_field_errors %} <div class="alert alert-danger"> <strong>{{ error|escape }} </strong> </div> {% endfor %} … -
DRF: Making external requests and building serializers
I'm using Django rest framework and on a POST request need to make an external request to a SOAP server which outputs weather reports. I receive something like this to my API { 'city': 'Manchester', 'country': 'GB', 'locality': 'EU' } Now this is the data I get. Serializing this data is fine and I get that. However since the SOAP address requires me to make a request within the following format I get confused. I haven't really tried anything but looking for a best solution in this. { 'geopgrahpy': { 'country': 'GB', 'city': 'Manchester', }, 'locality': 'EU', 'userID': '123', 'password': 'xxxxx' } My question is what would be the best solution? Manually building a util function which will return the userID, password (from the request) or build another serializer matching to the soap server needs. Also bear in mind I know SOAP is XML but the Zeep library converts it to and from XML. -
twilio multi factor authentication - Django Python
I am trying to implement a multi factor authentication on my Django web app , I went over some guides and answers but i am still confused , I want that after a user is login with his user name and password to have another step where he will get an SMS with one time token he will put it in the login and then he will be able to continue to the web app. I opened an account on Twillo , but here i got confused , in some example you need Authy and in some you dont ,i installed the Django OTP and Django two factor Auth , and i wasnt be able to bind them all together . Will relay appreciate an explanation on the different terms and how to bind them together. Thanks, Nir -
How to deserialize dates saved into Django s
I came across the “datetime.datetime not JSON serializable” error and wanted a clean Django solution for it So I tried to use DjangoJSONEncoder, but I didn t manage to deserialize the data after serializing it (I want to store it in a JSONField). I get a DeserializationError. What am I doing wrong ? This is what I came up so far : from django.utils.timezone import localtime, now from django.core.serializers.json import DjangoJSONEncoder from django.core.serializers import deserialize a = DjangoJSONEncoder().encode(localtime(now())) print(a) # "2019-07-31T16:48:19.665+02:00" b = deserialize("json",a) print(b) # <generator object Deserializer at 0x0000006CD0F35A40> for c in b : print(c) # django.core.serializers.base.DeserializationError PS : using Python 3.6.8 and Django 2.2.3. -
How to use TinyMCE 5 with Django?
There are no packages to support TinyMCE 5 for Django. The only available packages are version 3 or 4. I tried this guide https://www.tiny.cloud/docs/quick-start/ TinyMCE forms use native HTML and you have initialized it with javascript but Django forms work a different way. You have to make them in Views and I'm not that advanced to modify it. How should I go about that? -
Django query ValueError: hour must be in 0..23
I'm making a query through Django querysets and it's returning "ValueError: hour must be in 0..23" filtering the dates: In models.py: class handoff_model(models.Model): batch = models.ForeignKey(batch_def_model, on_delete=models.CASCADE) date = models.DateField(blank=True, null=True) class batch_def_model(models.Model): name = models.CharField(max_length=200) start_time = models.TimeField(blank=True, null=True) In views.py: def ho_open(request): date = '2019-07-29' all_b = batch_def_model.objects.all() for b in all_b: if not handoff_model.objects.filter(date=date, batch=b.name).exists(): batch = handoff_model(batch=b, date=date) batch.save() handoff_list = handoff_model.objects.filter(date=date,batch__start_time__lt='08:00') return handoff_list I already have a few "batch_def_model" objects in my database. Every time you run "ho_open" (changing the hardcoded date) it should create the handoff_models same as "batch_def_model" but for the hardcoded date. When I set the date as "2019-07-29" it works correctly. Whith date as "2019-07-30" or "2019-07-31" I get the following error: File "/usr/local/lib/python3.6/site-packages/django/db/backends/utils.py", line 151, in typecast_time return datetime.time(int(hour), int(minutes), int(seconds), int((microseconds + '000000')[:6])) ValueError: hour must be in 0..23 I'm not sure why it's not working with those dates because the entire month is working correctly. I've tested by filtering with date__contains=date without success. Do you have any hint? -
Why do the fields of the selected form return the value "none" and "null" in the database?
I am trying to save a value in the field 2 fields, but when saving them I change the value to "none" and in the db also in the field it shows me "null" I have tried to change the parentheses by the square brackets, seeing if the 2 values of the form are taken to the database, but I don't quite understand the difference between "form.cleaned_data () and form.cleaned_data []", but by doing so with the square brackets, it sends me an error my views.py def solit(request): if request.method == 'POST' and request.is_ajax(): form = addiForm(request.POST) if form.is_valid(): peticion = form.save(commit=False) peticion.usuario = request.user peticion.save() peticion.usuario.d_pendientes = form.cleaned_data.get('d_pendientes') peticion.usuario.h_pendientes = form.cleaned_data.get('h_pendientes') peticion.usuario.save() print (peticion.usuario.d_pendientes) print (peticion.usuario.h_pendientes) return JsonResponse({'status': 'true', 'msg': 'Procesado Correctamente'}) else: return JsonResponse({'status': 'false', 'msg': 'Los datos no son validos'}) form = addiForm() return render(request, 'plantillas/adicionar.html', {'form':form}) my models.py class Usuarios(AbstractUser): numero_empleado = models.IntegerField(null= True, blank= True) area = models.CharField(max_length = 200, null= True, blank= True) d_pendientes = models.IntegerField(null= True, blank= False) h_pendientes = models.IntegerField(null= True, blank= False) f_init = models.DateField(max_length = 200,null= True, blank= True) init_vac = models.DateField(max_length = 200, null= True, blank= True) fin_vac = models.DateField(max_length = 200, null= True, blank= True) ul_vac_tomadas = models.IntegerField(null= … -
Django: M2M database annotation query
Given the following models: User -------- Thread -------- Post -------- thread: ForeignKey(Thread) read_by: ManyToManyField(User) Now, I would like to retrieve all posts for a specific thread annotated if they are read by the currently logged in user. So, I start with fetching the posts: Post.objects.filter(thread=self.thread) Now, I am not sure how I can annotate with the read/unread flag set to True/False. The currently logged in user is available using the variable self.request.user. -
How to Improve the Efficiency of RESTful API Requests
I have a RESTful API request which returns upwards of 1,000 records in the form of JSON data. From this data I pull an ID to reference in a second API request to a different domain. The current logic results in slow page load times due to the large number of records being iterated through during the second request. How can I transition to 1+1 requests instead of 1+n in order to increase availability? views.py cw_presales_engineers = [] for opportunity in opportunities: try: opportunity_id = str(opportunity['id']) presales_ticket = cwObj.get_tickets_by_opportunity(opportunity_id) if presales_ticket: try: cw_engineer = presales_ticket[0]['owner']['name'] cw_presales_engineers.append(cw_engineer) except: pass else: cw_engineer = '' cw_presales_engineers.append(cw_engineer) except AttributeError: cw_engineer = '' first.request def get_opportunities(self): try: r = requests.get( self.URL + 'sales/opportunities?conditions=status/id=1 OR status/id=13 AND company/name!="XYZ Test Company" &pageSize=50& &oage=1& &orderBy=company/name asc&', headers=self.Header) r.raise_for_status() except: raise return r.json() second.request def get_tickets_by_opportunity(self, request): try: r = requests.get( self.URL + 'service/tickets?conditions=opportunity/id=' + request, headers=self.Header) r.raise_for_status() except: raise return r.json() -
how to replace value in dataset django
i've a dataset from a model with 40 fields, is there a smart way to replace a certain value(like NULL)? i've tried with nested for loops without success -
run postgres container when using docker
I have used cookiecutter-django for my django projects. I am using docker to run the project locally. The project is running well. However, i could not explore postgres while using docker. Here are the steps i followed to run the project docker-compose -f local.yml build docker-compose -f local.yml up -d docker-compose run django python manage.py makemigrations docker-compose run django python manage.py migrate local.yml looks like following version: '3' volumes: local_postgres_data: {} local_postgres_data_backups: {} services: django: &django build: context: . dockerfile: ./compose/local/django/Dockerfile image: travel_local_django depends_on: - postgres - mailhog volumes: - .:/app env_file: - ./.envs/.local/.django - ./.envs/.local/.postgres ports: - "8000:8000" command: /start postgres: build: context: . dockerfile: ./compose/production/postgres/Dockerfile image: travel_production_postgres volumes: - local_postgres_data:/var/lib/postgresql/data - local_postgres_data_backups:/backups env_file: - ./.envs/.local/.postgres compose/production/postgres/Dockerfile FROM postgres:11.3 COPY ./compose/production/postgres/maintenance /usr/local/bin/maintenance RUN chmod +x /usr/local/bin/maintenance/* RUN mv /usr/local/bin/maintenance/* /usr/local/bin \ && rmdir /usr/local/bin/maintenance .envs/.local/.postgres # PostgreSQL POSTGRES_HOST=postgres POSTGRES_PORT=5432 POSTGRES_DB=simplifytour POSTGRES_USER=debug POSTGRES_PASSWORD=debug when i did docker-compose -f local.yml ps, i get the container related to this project. I then executed the postgres container with command docker exec -it travel_postgres_1 sh. There i tried running the command like psql, psql -U postgres but nothing worked for me. I wanted to explore the postgres like listing the tables, connecting to the … -
django.db.utils.OperationalError: ('HYT00', '[HYT00] [Microsoft][ODBC Driver 17 for SQL Server]Login timeout expired (0) (SQLDriverConnect)')
I'm using. Django 2.1.10 Python 3.6.8 pyodbc 4.0.26 I have installed Microsoft ODBC Driver 17 for SQL Server. I want to connect to a SQL SERVER 2012 database, but when running "runserver" it shows the following error: Performing system checks... System check identified no issues (0 silenced). Unhandled exception in thread started by <function check_errors.<locals>.wrapper at 0x7f895628b9d8> Traceback (most recent call last): File "/mnt/c/Users/sistemas.GRUPOCONTROL/Desktop/CCONTROL/venvgcontrol/lib/python3.6/site-packages/django/db/backends/base/base.py", line 216, in ensure_connection self.connect() File "/mnt/c/Users/sistemas.GRUPOCONTROL/Desktop/CCONTROL/venvgcontrol/lib/python3.6/site-packages/django/db/backends/base/base.py", line 194, in connect self.connection = self.get_new_connection(conn_params) File "/mnt/c/Users/sistemas.GRUPOCONTROL/Desktop/CCONTROL/venvgcontrol/lib/python3.6/site-packages/sql_server/pyodbc/base.py", line 307, in get_new_connection timeout=timeout) pyodbc.OperationalError: ('HYT00', '[HYT00] [Microsoft][ODBC Driver 17 for SQL Server]Login timeout expired (0) (SQLDriverConnect)') The above exception was the direct cause of the following exception: Traceback (most recent call last): File "/mnt/c/Users/sistemas.GRUPOCONTROL/Desktop/CCONTROL/venvgcontrol/lib/python3.6/site-packages/django/utils/autoreload.py", line 225, in wrapper fn(*args, **kwargs) File "/mnt/c/Users/sistemas.GRUPOCONTROL/Desktop/CCONTROL/venvgcontrol/lib/python3.6/site-packages/django/core/management/commands/runserver.py", line 120, in inner_run self.check_migrations() File "/mnt/c/Users/sistemas.GRUPOCONTROL/Desktop/CCONTROL/venvgcontrol/lib/python3.6/site-packages/django/core/management/base.py", line 442, in check_migrations executor = MigrationExecutor(connections[DEFAULT_DB_ALIAS]) File "/mnt/c/Users/sistemas.GRUPOCONTROL/Desktop/CCONTROL/venvgcontrol/lib/python3.6/site-packages/django/db/migrations/executor.py", line 18, in __init__ self.loader = MigrationLoader(self.connection) File "/mnt/c/Users/sistemas.GRUPOCONTROL/Desktop/CCONTROL/venvgcontrol/lib/python3.6/site-packages/django/db/migrations/loader.py", line 49, in __init__ self.build_graph() File "/mnt/c/Users/sistemas.GRUPOCONTROL/Desktop/CCONTROL/venvgcontrol/lib/python3.6/site-packages/django/db/migrations/loader.py", line 212, in build_graph self.applied_migrations = recorder.applied_migrations() File "/mnt/c/Users/sistemas.GRUPOCONTROL/Desktop/CCONTROL/venvgcontrol/lib/python3.6/site-packages/django/db/migrations/recorder.py", line 61, in applied_migrations if self.has_table(): File "/mnt/c/Users/sistemas.GRUPOCONTROL/Desktop/CCONTROL/venvgcontrol/lib/python3.6/site-packages/django/db/migrations/recorder.py", line 44, in has_table return self.Migration._meta.db_table in self.connection.introspection.table_names(self.connection.cursor()) File "/mnt/c/Users/sistemas.GRUPOCONTROL/Desktop/CCONTROL/venvgcontrol/lib/python3.6/site-packages/django/db/backends/base/base.py", line 255, in cursor return self._cursor() File "/mnt/c/Users/sistemas.GRUPOCONTROL/Desktop/CCONTROL/venvgcontrol/lib/python3.6/site-packages/django/db/backends/base/base.py", line 232, in _cursor self.ensure_connection() File "/mnt/c/Users/sistemas.GRUPOCONTROL/Desktop/CCONTROL/venvgcontrol/lib/python3.6/site-packages/django/db/backends/base/base.py", line 216, … -
How to filter queryset value in one of the form fields using CreateView?
My task is to change the value of one field in the form (drop-down list with Foreignkey connection). I use CreateView and ModelForm. forms.py class SkillCreateForm(forms.ModelForm): def __init__(self, *args, **kwargs): super(SkillCreateForm, self).__init__(*args, **kwargs) employee_current_technology = Technology.objects.filter(??? --- How can I get editing user pk ????-----) self.fields['technology'].queryset = Technology.objects.exclude(name__in=employee_current_technology) I know that somehow I can get pk from url using kwarg and get_form_kwarg values, but I can't figure out how to do that. urls.py path('profile/<int:pk>/skill/create/', SkillCreateView.as_view(), name='skill_create'), views.py class SkillCreateView(AuthorizedMixin, CreateView): """ Create new course instances """ model = Skill form_class = SkillCreateForm template_name = 'employee_info_create.html' def get_form_kwargs(self): kwargs = super(SkillCreateView, self).get_form_kwargs() Employee.objects.get(pk=self.kwargs['pk']) -->get me pk ???? return kwargs ..... -
How can I set up international telephone input widget on Django crispy forms or any form tbh?
I tried using Django-intl-tel-input but the widget didn't load and had 404 errors in my terminal as mentioned in this question so I tried using the intl-tel-input and load the CSS/js files locally but the same problem happened so how can I make this work? I use Django-phonenumber-field to save the numbers in my model but I don't use it in my forms. I tried The Django-phonenumber-field widget and I didn't like that it wasn't so user-friendly. so what's the best way to integrate a phone number widget with country flags to the app? -
'Meta.fields' contains fields that are not defined on this FilterSet: EquipoOrigen
I present the following problem when trying to filter with fields of the serializer Interfaces that I am getting through foreign keys: 'Meta.fields' contains fields that are not defined on this FilterSet: Origin Team I need to be able to filter the fields EquipoOrigen, EquipoDestino, LocalidadOrigen How could I solve this? class Equipos(models.Model): id_equipo=models.PositiveSmallIntegerField(primary_key=True) nombre=models.CharField(max_length=15) vendedor=models.CharField(max_length=10,default='S/A',blank=True) ip_gestion=models.GenericIPAddressField(protocol='Ipv4',default='0.0.0.0') tipo=models.CharField(max_length=8,default='S/A',blank=True) localidad=models.CharField(max_length=5,default='S/A',blank=True) categoria=models.CharField(max_length=10,default='S/A',blank=True) ultima_actualizacion=models.DateTimeField(auto_now=True) class Meta: db_table = 'Equipos' class Puertos(models.Model): id_puerto=models.PositiveIntegerField(primary_key=True) nombre=models.CharField(max_length=25) ultima_actualizacion=models.DateTimeField(auto_now=True) class Meta: db_table='Puertos' class Interfaces(models.Model): id_interface=models.PositiveIntegerField(primary_key=True) id_EquipoOrigen=models.ForeignKey(Equipos,on_delete=models.DO_NOTHING,related_name='equipo_origen') id_PuertoOrigen=models.ForeignKey(Puertos,on_delete=models.DO_NOTHING,related_name='puerto_origen',null=True,blank=True) estatus=models.BooleanField(default=False) etiqueta_prtg=models.CharField(max_length=80,null=True,blank=True) grupo=models.PositiveSmallIntegerField(default=0,blank=True) if_index=models.PositiveIntegerField(default=0,blank=True) bw=models.PositiveSmallIntegerField(default=0,blank=True) bw_al=models.PositiveSmallIntegerField(default=0,blank=True) id_prtg=models.PositiveSmallIntegerField(default=0,blank=True) ospf=models.BooleanField(default=False) description=models.CharField(max_length=200,null=True,blank=True) id_EquipoDestino=models.ForeignKey(Equipos,on_delete=models.DO_NOTHING,related_name='equipo_destino') id_PuertoDestino=models.ForeignKey(Puertos,on_delete=models.DO_NOTHING,related_name='puerto_destino') ultima_actualizacion=models.DateTimeField(auto_now=True) class Meta: db_table='Interfaces' class InterfaceSerializer(serializers.ModelSerializer): EquipoOrigen = serializers.CharField(source='id_EquipoOrigen.nombre',read_only=True) PuertoOrigen = serializers.CharField(source='id_PuertoOrigen.nombre',read_only=True) LocalidadOrigen=serializers.CharField(source='id_EquipoOrigen.localidad',read_only=True) CategoriaOrigen=serializers.CharField(source='id_EquipoOrigen.categoria',read_only=True) EquipoDestino = serializers.CharField(source='id_EquipoDestino.nombre',read_only=True) PuertoDestino = serializers.CharField(source='id_PuertoDestino.nombre',read_only=True) LocalidadDestino=serializers.CharField(source='id_EquipoDestino.localidad',read_only=True) CategoriaDestino=serializers.CharField(source='id_EquipoDestino.categoria',read_only=True) class Meta: model=Interfaces fields=('id_interface','id_EquipoOrigen','EquipoOrigen','id_PuertoOrigen','PuertoOrigen','LocalidadOrigen','CategoriaOrigen','estatus','etiqueta_prtg','grupo','if_index','bw','bw_al','id_prtg','ospf','description','id_EquipoDestino','EquipoDestino','id_PuertoDestino','PuertoDestino','LocalidadDestino','CategoriaDestino','ultima_actualizacion',) class PostPageNumberPagination(PageNumberPagination): page_size=10 page_size_query_param = 'page_size' max_page_size = 1000 class InterfacesFilter(django_filters.FilterSet): class Meta: model=Interfaces fields= {'EquipoOrigen':['exact']} class InterfacesViewSet(viewsets.ModelViewSet): queryset=Interfaces.objects.all() serializer_class=InterfaceSerializer pagination_class=PostPageNumberPagination filter_class=InterfacesFilter -
How to select one element instead of all elements using 'clicked' in a Django for loop
In my Django project I am trying to create a feature so that when someone clicks the cog element on my folder, it adds a class to only the one folder element I have clicked. My issue is that when I click the cog, it apply's the class to all of the other folders, and not just the one I want. I understand why it is doing this, but not sure how to fix it. When I click the cog It applys the css to all elements and not just the one I clicked with the cog. HTML {% for video in videos %} {% if video.active %} <div class="folder"> <div class="folder-settings-tool" onclick="folderSettings(this)"> <!-- CHANGE COLOUR OF THE SETTINGS COG TO WHITE --> <img src="{% static 'public/image/icons/settings-work-tool.svg' %}"> </div> <div class="folder-settings"> <div class="title-change"> <p class="title-rename">RENAME</p><input type="text" name="title"> </div> <div class="archive"> <p class="archive-text"> ARCHIVE </p> <label class="switch"> <input type="checkbox"> <span class="slider round"></span> </label> </div> <div class="make-final"> <p class="archive-text"> MAKE FINAL </p> <label class="switch"> <input type="checkbox"> <span class="slider round"></span> </label> </div> <div class="downloadable"> <p class="archive-text"> DOWNLOADABLE </p> <label class="switch"> <input type="checkbox"> <span class="slider round"></span> </label> </div> </div> <a href="{% url 'public:file_detail' model='video' pk=video.pk %}"> <div class="folder-text"> <p>VIDEO</p> </div> <div class="image"> <img src="{% … -
How to edit .py File runtime
I have a simple error. I need to edit a .py file durring runtime and use that after the edit. Now i can edit and add my new lines to it. After running the script it comes to the exact position and runs it and creats the file the correct way but! I will get a 500 Error and the rest of the code will not be compiled. Following code i am running. with open("D:/django/alpha/alpha/settings_inspectdb2.txt", "a") as file: file.write("\t\t},") file.write("\n\t\t'" + projectname + "': {") file.write("\n\t\t\t\t'ENGINE': engine,") file.write("\n\t\t\t\t'NAME': " + projectname + ",") file.write("\n\t\t\t\t'USER': user,") file.write("\n\t\t\t\t'PASSWORD': pwd,") file.write("\n\t\t\t\t'HOST': host,") file.write("\n\t\t\t\t'PORT': port,") file.write("\n\t\t}") file.write("\n}") with open("D:/django/alpha/alpha/settings_inspectdb2.txt", 'r') as f1: lines = f1.readlines() with open("D:/django/alpha/api_manager/settings_inspectdbF.py", 'w+') as f2: for line in lines: f2.write(line) Does anyone know how to solve that error? -
why does site matching query not exist.?
I'm trying to do jwt authentication. I'm using some code from django-rest-auth package for registration and I have this problem for both registration endpoint and admin area. I know that a lot of people asked this question before me, but god knows why the solution isn`t working in my case. I`ve tried this in shell: >>> from django.contrib.sites.models import Site >>> site = Site() >>> site.domain = 'answerly.com' >>> site.name = 'answerly.com' >>> site.save() My settings: ... INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', # local apps 'pages', 'accounts', # third party packages 'rest_framework', 'rest_framework.authtoken', 'rest_auth', 'django.contrib.sites', 'allauth', 'allauth.account', 'rest_auth.registration', ] ... REST_USE_JWT = True ... Urls: from django.contrib import admin from django.urls import path, include from rest_auth.registration.views import RegisterView # from rest_auth.views import LoginView, LogoutView urlpatterns = [ path('admin/', admin.site.urls), path('', include('pages.api.urls')), path('accounts/registration/', RegisterView.as_view(), name='register'), # path('rest-auth/registration/', include('rest_auth.registration.urls')) ] I have this for the common solution: raceback (most recent call last): File "/home/valentyn/Dev/Answerly/venv/lib/python3.6/site-packages/django/db/backends/utils.py", line 84, in _execute return self.cursor.execute(sql, params) File "/home/valentyn/Dev/Answerly/venv/lib/python3.6/site-packages/django/db/backends/sqlite3/base.py", line 383, in execute return Database.Cursor.execute(self, query, params) sqlite3.IntegrityError: UNIQUE constraint failed: django_site.domain The above exception was the direct cause of the following exception: Traceback (most recent call last): File "<console>", line 1, in <module> … -
CSS attributes in HTML page show blank (style="") when they are not | NGINX + Django
All static files in the project are being loaded (how do I know this? Bootstrap, and Fontawesome, which I have locally, work fine), everything seems to be in order, but, for some reason, all the CSS attributes in the HTML pages are rendered blank when in the source code this is not the case. I haven't been able to find an answer online, and since I don't really know what files to include from my code or settings, I think a simple code sample of the problem should suffice. html source: <div style="width:100px;"></div> html live: <div style=""></div> I would give more information if I knew what would be useful. I don't know where the problem resides. I've never had this happen. -
AttributeError: 'module' object has no attribute 'compare_digest'
I configured user authorization via GoogleOauth2.0 (social-auth-app-django). Entries in the social_django / usersocialauth / application are not created. Locally everything works, but an error occurs on the server. After selecting an account to log in via Google, it redirects to the page complete/google-oauth2/ + GET paramteres In Traceback, I get the following: Traceback ERROR 2019-07-31 19:25:29,351 base 4745 139713585624832 Internal Server Error: /complete/google-oauth2/ Traceback (most recent call last): File "/home/deploy/.virtualenvs/finbee/lib/python2.7/site-packages/django/core/handlers/base.py", line 149, in get_response response = self.process_exception_by_middleware(e, request) File "/home/deploy/.virtualenvs/finbee/lib/python2.7/site-packages/django/core/handlers/base.py", line 147, in get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/home/deploy/.virtualenvs/finbee/lib/python2.7/site-packages/django/views/decorators/cache.py", line 57, in _wrapped_view_func response = view_func(request, *args, **kwargs) File "/home/deploy/.virtualenvs/finbee/lib/python2.7/site-packages/django/views/decorators/csrf.py", line 58, in wrapped_view return view_func(*args, **kwargs) File "/home/deploy/.virtualenvs/finbee/lib/python2.7/site-packages/social_django/utils.py", line 49, in wrapper return func(request, backend, *args, **kwargs) File "/home/deploy/.virtualenvs/finbee/lib/python2.7/site-packages/social_django/views.py", line 33, in complete *args, **kwargs) File "/home/deploy/.virtualenvs/finbee/lib/python2.7/site-packages/social_core/actions.py", line 43, in do_complete user = backend.complete(user=user, *args, **kwargs) File "/home/deploy/.virtualenvs/finbee/lib/python2.7/site-packages/social_core/backends/base.py", line 40, in complete return self.auth_complete(*args, **kwargs) File "/home/deploy/.virtualenvs/finbee/lib/python2.7/site-packages/social_core/utils.py", line 251, in wrapper return func(*args, **kwargs) File "/home/deploy/.virtualenvs/finbee/lib/python2.7/site-packages/social_core/backends/oauth.py", line 388, in auth_complete state = self.validate_state() File "/home/deploy/.virtualenvs/finbee/lib/python2.7/site-packages/social_core/backends/oauth.py", line 91, in validate_state elif not constant_time_compare(request_state, state): File "/home/deploy/.virtualenvs/finbee/lib/python2.7/site-packages/social_core/utils.py", line 227, in constant_time_compare return hmac.compare_digest(val1, val2) AttributeError: 'module' object has no attribute 'compare_digest' settings.py MIDDLEWARE_CLASSES = ( 'django.contrib.auth.middleware.AuthenticationMiddleware', 'social_django.middleware.SocialAuthExceptionMiddleware', ) TEMPLATES … -
How to disallow creation of object if related foreign key doesn't exists?
Here is the setup class A(Model): pass class B(Model): a = ForeignKey(A, on_delete=CASCADE) assert A.objects.all().count() == 0 try: B(a_id=1) except IntegrityError: print('error') # ... another logic to deal with situation DB is PostgreSQL. There are no A objects yet (at least with id=1). I try to create object B using the id of some hypothetical object A fetched from the 3rd party. Expectation If there is no object A -> IntegrityError is thrown -> deal with it (eg create object A with id=1 and rerun). Reality Object B is created anyway despite having a foreign key constraint, IntegrityError is thrown but is not fetched by try/except. Everything is messed up. I don't what to get_or_create object A beforehand because I will end up with 2 queries every time I want to create B (and I need to create it many times while most of the time needed object A is already in DB) -
Django contact form doesnt submit
I am trying to set up a contact form. I have implemented the Django-crispy-forms and now my form is not submitted (I don't have any errors). I've added action="" to my form in my template without any success. forms.py class ContactForm(forms.Form): name = forms.CharField(max_length=100, help_text='Enter your name or username') email = forms.EmailField() message = forms.CharField(widget=forms.Textarea(attrs={'rows': 3, 'cols': 40}), help_text='Example: I forgot my password!') views.py def contact_us(request): if request.method == 'POST': form = ContactForm(request.POST) if form.is_valid(): sender_name = form.cleaned_data['name'] sender_email = form.cleaned_data['email'] message = "From {0}:\n\n{1}".format(sender_name, form.cleaned_data['message']) send_mail('PLM_Tool contact', message, sender_email, ['myadress@gmail.com']) return redirect('home:index') else: form = ContactForm() return render(request, 'accounts/contact.html', {'form': form}) urls.py app_name = 'accounts' urlpatterns = [path('contact/', views.contact_us, name='contact'),] contact.html {% extends "base.html" %} {% load crispy_forms_tags %} {% block main %} <form method="post" action=""> {% csrf_token %} <div class="row"> <div class="col-6"> {{ form.name|as_crispy_field }} </div> <div class="col-6"> {{ form.email|as_crispy_field }} </div> <div class="col-6"> {{ form.message|as_crispy_field }} </div> </div> </form> <button type="submit" class="btn btn-success">Send</button> <a href="{% url 'home:index' %}" class="btn btn-danger">Cancel</a> <br><br> {% endblock %} -
How to parse XML into Django model?
I have Playlist and Track models. Playlist has XML-file field, Track has Playlist as a foreign key. From where I shoud run python parser script to parse XML into Track instances as soon as I add new Playlist instance? -
How to control color theme using configurations in Django admin?
Basically I have Django project (using Docker) installed on many sites with different logos, content, etc. Problem seems to be that also theme colors should be configurable for each site. Optimal solution would be to have some color codes (primary, secondary, etc) configurable, which would eventually change CSS content. Project uses Bootstrap 4, which uses SASS (SCSS) that compiles as CSS, so now my GIT contains single SCSS file and compiled final CSS should be different on each site. All solutions I have figured out seem to be hacks, so I wonder is there any "clean solutions" for this? Solution don't have to be necessarily "real time", like configurations in Django Admin UI, but that would definitely be plus. Anyway, something that works even if I make changes to common code base and update that to all sites.