Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
django.db.utils.OperationalError: FATAL: password authentication failed for user "vagrant"
I had a problem with my vagrant boxes with ports and everything so I did something that I suspect is inhibiting my ability to run ./manage.py migrate. Here's what it looks like when I run vagrant ssh-config HostName 127.0.0.1 User vagrant Port 2222 UserKnownHostsFile /dev/null StrictHostKeyChecking no PasswordAuthentication no IdentityFile /Users/brock1hj/projects/sodium/to-vagrant/.vagrant/machines/default/virtualbox/private_key IdentitiesOnly yes LogLevel FATAL Here is the full error: Traceback (most recent call last): File "./manage.py", line 10, in <module> execute_from_command_line(sys.argv) File "/Users/brock1hj/envs/sodium/lib/python2.7/site-packages/django/core/management/__init__.py", line 338, in execute_from_command_line utility.execute() File "/Users/brock1hj/envs/sodium/lib/python2.7/site-packages/django/core/management/__init__.py", line 330, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/Users/brock1hj/envs/sodium/lib/python2.7/site-packages/django/core/management/base.py", line 390, in run_from_argv self.execute(*args, **cmd_options) File "/Users/brock1hj/envs/sodium/lib/python2.7/site-packages/django/core/management/base.py", line 441, in execute output = self.handle(*args, **options) File "/Users/brock1hj/envs/sodium/lib/python2.7/site-packages/django/core/management/commands/migrate.py", line 93, in handle executor = MigrationExecutor(connection, self.migration_progress_callback) File "/Users/brock1hj/envs/sodium/lib/python2.7/site-packages/django/db/migrations/executor.py", line 19, in __init__ self.loader = MigrationLoader(self.connection) File "/Users/brock1hj/envs/sodium/lib/python2.7/site-packages/django/db/migrations/loader.py", line 47, in __init__ self.build_graph() File "/Users/brock1hj/envs/sodium/lib/python2.7/site-packages/django/db/migrations/loader.py", line 180, in build_graph self.applied_migrations = recorder.applied_migrations() File "/Users/brock1hj/envs/sodium/lib/python2.7/site-packages/django/db/migrations/recorder.py", line 59, in applied_migrations self.ensure_schema() File "/Users/brock1hj/envs/sodium/lib/python2.7/site-packages/django/db/migrations/recorder.py", line 49, in ensure_schema if self.Migration._meta.db_table in self.connection.introspection.table_names(self.connection.cursor()): File "/Users/brock1hj/envs/sodium/lib/python2.7/site-packages/django/db/backends/base/base.py", line 162, in cursor cursor = self.make_debug_cursor(self._cursor()) File "/Users/brock1hj/envs/sodium/lib/python2.7/site-packages/django/db/backends/base/base.py", line 135, in _cursor self.ensure_connection() File "/Users/brock1hj/envs/sodium/lib/python2.7/site-packages/django/db/backends/base/base.py", line 130, in ensure_connection self.connect() File "/Users/brock1hj/envs/sodium/lib/python2.7/site-packages/django/db/utils.py", line 97, in __exit__ six.reraise(dj_exc_type, dj_exc_value, traceback) File "/Users/brock1hj/envs/sodium/lib/python2.7/site-packages/django/db/backends/base/base.py", line 130, in ensure_connection self.connect() File "/Users/brock1hj/envs/sodium/lib/python2.7/site-packages/django/db/backends/base/base.py", line 119, in … -
Django : cannot unpack non-iterable int object
i'm learning django and Python. I have a problem with a form. the error is "TypeError at /My_app" and "cannot unpack non-iterable int object" this is my views : from django.http import HttpResponse, Http404 from django.shortcuts import redirect, render, get_object_or_404 from datetime import datetime from Qualite.forms import NCForm from Qualite.models import NC, Nc_type, Poste def view_accueil(request): form = NCForm(request.POST or None) if form.is_valid(): newNc = NC() newNc.idaffaire = form.cleaned_data['idaffaire'] newNc.idnc = form.cleaned_data['idnc'] newNc.idof = form.cleaned_data['idof'] newNc.idposte = form.cleaned_data['idposte'] newNc.idrepere = form.cleaned_data['idrepere'] newNc.iquantite = form.cleaned_data['iquantite'] newNc.save() return render(request, 'Qualite/accueil.html', locals()) my forms : from django import forms from .models import Nc_type, NC, Poste class NCForm(forms.Form): #choices = NC.objects.values_list('id', 'idaffaire') ncs = NC.objects.values_list('idaffaire', flat = True) idaffaire = forms.ChoiceField(choices = (ncs)) idof = forms.CharField() idrepere = forms.CharField() idposte = forms.CharField() idnc = forms.CharField() quantite = forms.CharField() and my model from django.db import models from django.utils import timezone class Nc_type(models.Model): nom = models.CharField(max_length=30) def __str__(self): return self.nom class Poste(models.Model): nom = models.CharField(max_length=50) def __str__(self): return self.nom class NC(models.Model): idaffaire = models.CharField(max_length=4, db_column='idAffaire') idof = models.IntegerField(db_column='idOf') idposte = models.ForeignKey('Poste', models.DO_NOTHING, db_column="idPoste", default=1) idrepere = models.IntegerField(db_column='idRepere') idnc = models.ForeignKey(Nc_type, models.DO_NOTHING, db_column='idNc_type', default=1) quantite = models.PositiveIntegerField() dateajout = models.DateTimeField(default=timezone.now, db_column='dateAjout') and the template: <h1>Ajout d'une NC</h1> … -
Django foreign key form.save() issue
I am new to Django and trying to create a signup view by using a form with a model extension of User model from django.contrib.auth.models and the UserCreations forms as below however a database error occurred after I submit the signup form in the server: ORA-01400: cannot insert NULL into (The foreign key) I thought the key will be generated automatically indeed. What is the problem?truly appreciate your help!! Below is the views: from django.contrib.auth.forms import UserCreationForm, AuthenticationForm from django.http import HttpResponse from django.shortcuts import render,redirect from django.contrib.auth import authenticate, login, logout from .forms import signupform def signup_view(request): if request.method =='POST': form = UserCreationForm(request.POST) s_form= signupform(request.POST) if form.is_valid()and s_form.is_valid(): user =form.save() s_form.save() login(request,user) return redirect("../") else: form =UserCreationForm() s_form = signupform() return render(request,'signup.html',{'form':form,'s_form': s_form}) Here is the forms from django import forms from django.contrib.auth.models import User from .models import Profile class signupform(forms.ModelForm): error_messages = { 'password_mismatch': ("The two password fields didn't match."), } F_name = forms.CharField(label=("First Name")) L_name = forms.CharField(label=("Last Name")) Date_of_birth = forms.DateField() email = forms.EmailField(widget=forms.TextInput( attrs={'type': 'email', 'placeholder': ('E-mail address')})) phone = forms.CharField() class Meta: model = Profile fields = ("F_name", "L_name", "Date_of_birth", "email") def save(self, commit=True): user = super(signupform, self).save(commit=False) if commit: user.save() return user Here is … -
Resize chrome browser window
The minimum width of google chrome can be only 500 pixels but I want it to be reduced to 320 pixels, for that what should I do or is there any extension or something else for that?? -
I am getting AttributeError in RequestContext in DJango
I am using Django. I have pip installed typeform sdk using https://pypi.org/project/django-typeform/ I wanted Pass URL parameter in iframe issue as mentioned Passing URL parameter in iframe issue I tried using following https://glitch.com/edit/#!/tf-embed-with-params?path=README.md:1:0 Traceback: Exception Type: AttributeError Exception Value: 'RequestContext' object has no attribute 'META' views.py from django.shortcuts import render from django.template import RequestContext def survey(request): return render(RequestContext(request),'wfhApp/survey.html') And my html page is as follow: <!DOCTYPE html> {% load django_typeform %} {% load sekizai_tags %} <html> <head> <title>Hello!</title> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" href="/styles.css"> </head> <body> <h1>Hi there!</h1> <div class="target-dom-node" style="width: 100%; height: 500px;"></div> <script src="https://embed.typeform.com/embed.js"></script> <script src="/survey/script.js"></script> {% typeforms_embed 'https://theother2thirds.typeform.com/to/hNZW30' 'New typeform' '{"hideHeaders": true, "hideFooter": true}' %} </body> </html> -
Google pubsub Async pulling blocked forever when called within Django manage.py shell
Context: Pull messages from a Google pubsub subscription from a django manage.py script and store filtered messages in the backend. the snippet of the code that runs under def handle(self, *args, **options) is as follows (https://github.com/GoogleCloudPlatform/python-docs-samples/blob/master/pubsub/cloud-client/quickstart/sub.py): from google.cloud import pubsub_v1 subscriber_client = pubsub_v1.SubscriberClient() subscription_path = subscriber_client.subscription_path( project_id, subscription_name ) def callback(message): print( "Received message {} of message ID {}\n".format( message, message.message_id ) ) # Acknowledge the message. Unack'ed messages will be redelivered. message.ack() print("Acknowledged message {}\n".format(message.message_id)) streaming_pull_future = subscriber_client.subscribe( subscription_path, callback=callback ) print("Listening for messages on {}..\n".format(subscription_path)) try: streaming_pull_future.result() except: # noqa streaming_pull_future.cancel() subscriber_client.close() The same code works as expected when ran outside of the manage.py command using python3 script.py but blocked/waiting on subscriber_client.subscribe without any output if called inside Django management command without any exception. Probably issue is related to concurrent.futures. Thanks in advance -
How to add "annotate" data into query with several "values" with django models?
Example model: class A(models.Model): id = models.CharField(max_length=255, primary_key=True, default=make_uuid, editable=False) b = models.IntegerField() Goal: I need to get list which would contain id, b and same_b_total. e.g. following quetyset returns: a = list(models.Cell.objects.all().values("b").annotate(same_b_total=Count("b"))) print(a) # [{"b": 1, "same_b_total": 5}, {"b": 2, "same_b_total": 3}] When I add id into .values("b", "id") it return list with followind data [{'b': 1, 'id': '<some uuid>', 'same_b_total': 1}, {'b': 1, 'id': '<some uuid2>', 'same_b_total': 1}, {'b': 2, 'id': '<some uuid3>', 'same_b_total': 1}, ...] How to change query to receive correct same_b_total for each record? Like: [{'b': 1, 'id': '<some uuid>', 'same_b_total': 5}, {'b': 1, 'id': '<some uuid2>', 'same_b_total': 5}, {'b': 2, 'id': '<some uuid3>', 'same_b_total': 3}, ...] -
No Dynos is running for Django web app on Heroku
I am working on a web app that i have made using Python, Django. After completed this app in development I have decided to host the app on Heroku so that other peoples will also visit my website to do so I signed up on Heroku and create a new app. I then pushed my app to heroku using git but whenever I visit url I get: Application error An error occurred in the application and your page could not be served. If you are the application owner, check your logs for details. You can do this from the Heroku CLI with the command heroku logs --tail When I go to resource page of my app I realize that there is no dyno instance running. I check the logs and I'm getting a H14 - No web processes running.Which suggest that my app has no dyno's indeed. I tried a lot of solution from internet and have searched all stack overflow questions related to this problem but my problem still not solved: Here is the command in my Procfile: web: gunicorn MyFirstWebsite.wsgi --log-file - Any help would be really appreciated. -
Line ChartJs does not render - Date format issue
I am trying to plot a line chart using Django and ChartJs. I created a list of dates in my view file that I would like to use as x-axis data in my chart. I rendered my list of dates in my template through built-in template tags {{ date }}. When I run the server and open my template, no issue appears, even the chart. When I inspect my html file, the list has “'” prior each date element in my list (I attached a capture). enter image description here I think this is why it does not work but I can’t figure out why I have this text in my list. I'm assuming that this is the index. I tried to convert my dates list into string but it is still the same. Do you guys have any idea ? Thank you for your help. [from django.shortcuts import render import yfinance as yf import pandas as pd from datetime import datetime as dt def HomeView(request, *args, **kwargs): data = yf.download(tickers='SAF.PA') data\['Date'\] = data.index data\['Date'\] = data\['Date'\].dt.strftime("%Y-%m-%d") context = { "Date" : data.Date\[0:5\].tolist(), "Close" : data.Close\[0:5\].tolist() } return render(request, "home.html", context)][1] -
TypeError: on_delete must be callable. ('on_delete must be callable.')
I have done a project three month before. Now when i downloaded the code from github and run the server I am facing this issue. "/home/shivam/.local/lib/python3.6/site-packages/django/db/models/fields/related.py", line 801, in init raise TypeError('on_delete must be callable.') TypeError: on_delete must be callable. My files are. models.py from django.db import models from django.contrib.auth.models import User # Create your models here. class Book(models.Model): title = models.CharField(max_length=100) price = models.FloatField() author = models.CharField(max_length=100) publisher = models.CharField(max_length=100) def __str__(self): return self.title class BRMuser(models.Model): user = models.OneToOneField(User,on_delete="models.CASCADE") nickname = models.CharField(max_length=20,null=False) def __str__(self): return self.nickname views.py from django.shortcuts import render from BRMapp.forms import NewBookForm,SearchForm from BRMapp.models import Book from django.http import HttpResponse,HttpResponseRedirect from django.contrib.auth import authenticate, login,logout # Create your views here. def userLogin(request): data = {} if request.method == "POST": username = request.POST['username'] password = request.POST['password'] user = authenticate(username=username,password=password) if user: login(request, user) return HttpResponseRedirect('/BRMapp/view-books') else: data['error']="UserName and Password are incorrect" res = render(request,'BRMapp/user_login.html', data) return res else: return render(request,'BRMapp/user_login.html',data) def userLogout(request): logout(request) return HttpResponseRedirect('BRMapp/login/') def viewBooks(request): books = Book.objects.all() res=render(request,'BRMapp/view_book.html',{'books':books}) return res def editBook(request): book = Book.objects.get(id=request.GET['bookid']) fields= {'title':book.title,'price':book.price,'author':book.author,'publisher':book.publisher} form = NewBookForm(initial=fields) res = render(request,'BRMapp/edit_book.html', {'form':form, 'book':book}) return res def deleteBook(request): bookid = request.GET['bookid'] book = Book.objects.get(id=bookid) book.delete() return HttpResponseRedirect('view-books') def searchBook(request): form = SearchForm() res … -
{{ object.count }} do not work , in my case it is student.count , what could be a reason? [closed]
{% extends 'base.html' %} {% block content %} <p> <a href="{% url 'student_edit' student.pk %}">Edit This Admission(E)</a> <br> </p> <p> <a href="{% url 'student_delete' student.pk %}">Delete This Admission(-)</a> <br> </p> <div class="post-entry"> <h2>{{ student.fname }}</h2> <h3>{{ student.lname }}</h3> <p>{{ student.count }}</p> </div> {% endblock content %} -
How do I integrate a django front-end interface for a tensorflow model?
like the header suggests, I would like to integrate a django front end page and a tensorflow model namely the image translation one called pix2pix, a port done by affine-layer. I'm very new to tf and I've read a lot of pages and tutorials and such but I just can't seem to understand. Can someone help? -
Filtering searches with Django
I'm trying to add filters to my search with Django_Filters. But when I try to filter an already existing search, the ?q=mysearch is eliminated and after that the filters are applied. This is the code: def get_queryset(self): #this is the search part qs = self.model.objects.all().order_by('id') search = self.request.GET.get('q') if search: qs = qs.filter(Título__icontains=search) return qs def get_context_data(self, **kwargs): #here's when I try to filter context = super().get_context_data(**kwargs) MyFilter = PubFilters(self.request.GET, queryset=self.get_queryset()) queryset = MyFilter.qs search = self.request.GET.get('q') paginator, page, object_list, is_paginated = self.paginate_queryset( queryset, self.get_paginate_by(queryset) ) queries = self.request.GET.copy() queries.pop('page', None) context.update( filter=MyFilter, filtered_items=object_list, page=page, is_paginated=is_paginated, count=paginator.count, queries=queries, búsqueda=self.request.GET.get('q') ) return context Any idea on how to solve this? If you need any other piece of code, please ask. Thanks in advance! -
Deploying dockerized Django with channels + Nginx + Daphne
i have a django application, running in Docker, which is using channels 2 (for a chat app). When running docker-compose up on local, the site and websocket chat works like a charm. Now i tried to deploy the project: I want to run the whole project only on ASGI with daphne (instead of Daphne for Websocket and gunicorn for standard requests). Well, i tried it for three days now, i dont get it working. I am completey lost. The website with "standard" http requests over https is working perfect, the chat with websockets gives me a 500 error, but the error message is a miracle to me. I have really no idea, what to do next. (have to say, i am a beginner in django, nginx and websockets) My setup is: Django, Django Channels, Redis, Nginx, Docker, Daphne Django Projectname is xtools This is my production docker-compose: version: '3.7' services: web: container_name: 'web' build: context: ./app dockerfile: Dockerfile.prod command: daphne -b 0.0.0.0 -p 8000 xtools.asgi:application volumes: - static_volume:/home/app/web/static - media_volume:/home/app/web/mediafiles expose: - 8000 env_file: - ./.env.prod depends_on: - db networks: - docker-network redis: image: redis:latest command: ["redis-server", "--bind", "redis", "--port", "6379"] db: image: postgres:12.0-alpine volumes: - postgres_data:/var/lib/postgresql/data/ env_file: - ./.env.prod.db … -
Python Django Best Practice for request.user in Class Based Views and Queryset
I am using class based views and have always the same problem without an elegant solution. My querysets should only show the ones that are owned of the request user. Code view: class MyListView(ListView): model = MyModel def get_queryset(self): return self.model.objects.owned_by_user(self.user) def __init__(self, **kwargs): super().__init__(**kwargs) self.user = None def dispatch(self, request, *args, **kwargs): self.user = request.user return super().dispatch(request, *args, **kwargs) model: class MyModelQuerySet(models.QuerySet): def owned_by_user(self, user): return self.filter(user_field=user) class MyModelManager(models.Manager): def get_queryset(self): return MyModelQuerySet(self.model, using=self._db) def owned_by_user(self, user): return self.get_queryset().owned_by_user(user) class MyModel(models.Model): user_field = ... objects = ProductRequestManager() Best practice 1: I think I have to overwrite dispatch to add the request.user. My IDE notes "Instance attribute user defined outside of init. In order to prevent this I also need to overwrite init(). How can I achieve this with less code? Best practice 2: Is there another way to get querysets belonging to the current user? -
Conditional search in django filter
I want to retrieve some data from my database in this way from .models import Student #activity is a many to many field students = Student.objects.filter(name="doe",activity__name__icontains='a' or 'b').distinct().all() This will work 👆. But my problem is I have a list of items to check against the activities and if I try it like this 👇... it fails activities = ['a','b','c'] students = Student.objects.filter(name="doe",activity__name__icontains=activities).distinct().all() The length of the list is not constant it always varies. I would appreciate any helping hand. Thank you -
Unable to update existing formets
community! I am new here. I have been working on this issue for the past couple of days. Could someone help me, please? Problem: Unable to edit/delete existing formsets I have 1 form and 2 formsets in my view. I am able to create all 3, successfully. Template rendering 1 form and 2 formsets Also, I can edit/delete the form, but can't with the 2 formsets. models.py class Component(models.Model): ... class ComponentImage(models.Model): component = models.ForeignKey(Component, on_delete=models.CASCADE, related_name='componentimage') image = models.ImageField(upload_to='component_pics') caption = models.CharField(max_length=100, null=True, blank=True) class ComponentWeblink(models.Model): component = models.ForeignKey(Component, on_delete=models.CASCADE, related_name='componentweblink') url = models.URLField() caption = models.CharField(max_length=100, null=True, blank=True) views.py def component_create(request): template = 'component/component_add.html' if request.method == 'GET': form = ComponentForm() images = ImageFormset(queryset=ComponentImage.objects.none(), prefix='images') links = WeblinkFormset(queryset=ComponentWeblink.objects.none(), prefix='links') elif request.method == 'POST': form = ComponentForm(request.POST) images = ImageFormset(request.POST, request.FILES, prefix='images') links = WeblinkFormset(request.POST, prefix='links') if form.is_valid() and images.is_valid() and links.is_valid(): component = form.save(commit=False) component.updated_by = request.user component.save() for form in images: if form.has_changed(): componentimage = form.save(commit=False) componentimage.component = component componentimage.updated_by = component.updated_by try: componentimage.save() except ValueError: pass for form in links: if form.has_changed(): componentweblink = form.save(commit=False) componentweblink.component = component componentweblink.updated_by = component.updated_by componentweblink.save() messages.success(request, 'Component successfully created.') return HttpResponseRedirect(reverse_lazy('component:component_detail', args=(component.pk,))) return render(request, template, { 'form': form, 'images': … -
Django treating DateTimeField as both UTC and America/Chicago
In my views.py I am both writing to and reading from a PostgreSQL table that has a DateTimeField. When creating a new entry, the date field is populated in UTC time. When pulling the data from the database in views.py the UTC timestamp is being treated as though it is in the timezone "America/Chicago". # settings.py TIME_ZONE = 'America/Chicago' USE_I18N = True USE_L10N = True USE_TZ = True I've tried supplying varios timezone aware dates when creating the entry in the database but it always appears as UTC when viewing the database directly. When I pull the data back django is treating the UTC datetime as if the timezone were "America/Chicago" # views.py CT = pytz.timezone("America/Chicago") UTC = pytz.timezone("UTC") # attempt_1 = datetime.datetime.utcnow().astimezone(CT) # attempt_2 = datetime.datetime.now().astimezone(CT) # attempt_3 = datetime.datetime.utcnow() attempt_4 = datetime.datetime.utcnow().astimezone(UTC) new_entry = MyModel(date=attempt_4) new_entry.save() -
django forms post request raising an error on __init__ method
I have a django form which takes a paramater from the view to initialize the MultipleChoiceField based on the user instance. The form is working fine when loading the template. when i submit the form the init method in the form raising an error. My Model models.py from django.db import models from django.contrib.auth.models import User class Group(models.Model): group_name = models.CharField('Group name', max_length=50) def __str__(self): return self.group_name class GroupMembers(models.Model): group_name = models.ManyToManyField(Group) members = models.ForeignKey(User, on_delete=models.CASCADE) class Transactions(models.Model): bill_type = models.CharField('Bill type',max_length=200) added_by = models.ForeignKey(GroupMembers, on_delete=models.CASCADE) added_to = models.ForeignKey(Group, on_delete=models.CASCADE) purchase_date = models.DateField(auto_now=True) share_with = models.CharField('Share among',max_length=250) amount = models.IntegerField(default=0) def __str__(self): return self.bill_type forms forms.py from django import forms from .models import Transactions, GroupMembers class Bill_CreateForm(forms.ModelForm): def __init__(self, user_list, *args, **kwargs): super(Bill_CreateForm, self).__init__(*args, **kwargs) self.fields['share_with'] = forms.MultipleChoiceField(widget=forms.CheckboxSelectMultiple,choices=tuple([(name, name.members) for name in user_list])) class Meta: model = Transactions fields = ( 'bill_type', 'amount', 'added_by', 'added_to', 'share_with', ) views views.py from django.shortcuts import render, redirect from django.contrib.auth.models import User from .models import Transactions, Group, GroupMembers from .forms import Bill_CreateForm from django.http import HttpResponse, HttpResponseRedirect def add_bills_home(request, id=None): user = User.objects.get(pk=id) grpname = Group.objects.filter(groupmembers__members=user) gm = GroupMembers.objects.filter(group_name__group_name=grpname[0]) users_list = [i for i in gm] if request.method == 'POST': form = Bill_CreateForm(request.POST) if form.is_valid(): … -
Django : is there a way to create a popup window without the use of a template file?
I'm accessing instruments from a Django application (sorry if I don't use the right terms I am not a developper). One of the instrument we use must do the same measurement a few times : Once the instrument has made an acquisition, the user must do some things, inform the application, so it can starts the next acquisition. I wanted to make everything from the view to make it simpler. So basically I need to make a popup window before the acquisition, and wait for the user to close this window to start the acquisition. The messages from django need some lines in the template, but I'd like to do all this before accessing the template ? Is that possible ? Thank you for your answers ! -
Django send http response without changing page
In django, if i wanted to send back a return httpresponse but not make a new page eg: when i send a http response it becomes https://localhost:8000/appname/submit/, i want to send an http response to https://localhost:8000/appname/ and not change it? I just want a general answer nothing specialised, if any code is needed please tell me. From my research i found a question with a very similar title unfortunately it is for flask or ajax and not django focused [yes i might be able to work it out but i recently just started django so it's a bit confusing :) ] -
Header refuses to show up on mobile view
I've spent a week trying to figure this out. I'm building a django website, and I have a navigation menu that always remains hidden behind some element when I look at the website on my mobile view. On Chrome Dev Tools, it looks perfectly fine, but on my phone, it's completely gone. Example of Chrome Dev Tools vs Phone: My first step in solving this was looking at the z-index. None of the indexes I tried worked, and I made sure to search for solutions to z-indexes not working on the Internet as well, such as having necessary prerequisites. Since my navigation menu is in my base.html template file, I even moved the header down to the very bottom of the body element (it has a fixed position), so that {%block content%} was always above the header. That didn't work either. So I tried moving all elements to the left whenever the navbar was open. This is what happened. If I try inspecting this on chrome dev tools by right clicking the empty space where there should be empty space, I get the following: ...meaning the only thing that's there is the HTML file itself. I'm completely baffled. I have … -
List and Put method
I'm new to django-framework. I'm trying to list and create two models at the same time. But I'm unable to bring the data of the two models in a single json models.py class User(models.Model): id=models.CharField(max_length=9,primary_key=True) name=models.CharField(max_length=30) def __str__(self): return self.name class ActivityPeriod(models.Model): tz=models.CharField(max_length=30) start_time=models.DateTimeField(auto_now=False, auto_now_add=False) end_time=models.DateTimeField(auto_now=False, auto_now_add=False) activityperiod2user=models.ForeignKey(User,related_name='activityperiods', on_delete=models.CASCADE) def __str__(self): return str(self.activityperiod2user) views.py class CustomApiView(generics.ListCreateAPIView): queryset = User.objects.all() serializer_class = serializers.CustomSerializer serializers.py class CustomUserSerializer(serializers.ModelSerializer): class Meta: model=models.User fields=("__all__") class CustomSerializer(serializers.ModelSerializer): activitydata=CustomUserSerializer() class Meta: model=models.User fields=('name','activitydata') -
Django FileField wont update path and url after save()
I have this model: class Galeria(models.Model): galeriaid = models.AutoField(db_column='GaleriaID', primary_key=True) nombre = models.CharField(db_column='Nombre', max_length=128, blank=True, null=True) ruta = models.FileField(db_column='Ruta', max_length=512, blank=True, null=True) And I overrided the save() to make my file look like {pk}.jpg or {pk}.mp4. The code works but it doesnt update the file.path and file.url. I get "media/{file}" instead of "media/imagenes/%Y%m/{file}". What am I doing wrong, the save() code below: def save( self, force_insert=False, force_update=False, *args, **kwargs): # Call save for post id super( Galeria, self ).save( *args, **kwargs ) ruta = self.ruta if ruta: # Create new file using pk and ext file oldfile = self.ruta.name dot = oldfile.rfind( '.' ) newfile = str( self.pk ) + oldfile[dot:] # Create new file and remove the old one if newfile != oldfile: self.ruta.storage.delete( newfile ) if newfile.endswith(".jpg"): self.ruta.storage.save( "imagenes/" + str(timezone.now().strftime("%Y/%m/")) + str(newfile), ruta ) elif newfile.endswith(".mp4"): self.ruta.storage.save( "videos/" + str(timezone.now().strftime("%Y/%m/")) + str(newfile), ruta ) else: self.ruta.storage.save( newfile, ruta ) self.ruta.name = newfile self.ruta.close() self.ruta.storage.delete( oldfile ) # keep the changes super( Galeria, self ).save( *args, **kwargs ) I tried adding a function to upload to, but still doesnt work. -
django channels project deploy on heroku
I cant deploy a Django channels app to Heroku. Django rest is deployed successfully but I can't connect to sockets from Heroku host when I try, I get error "ws/... not found" I think that problem is on settings of ASGI hosts, maybe I type incorrect host? REDISTOGO_URL: redis://redistogo:<key>@hammerjaw.redistogo.com:10388/ on my setting.py I write this: ASGI_APPLICATION = 'hahachat.routing.application' CHANNEL_LAYERS = { 'default': { 'BACKEND': 'asgi_redis.RedisChannelLayer', 'CONFIG': { "hosts": [ ('hammerjaw.redistogo.com', 10388) ], }, }, } routing application application = ProtocolTypeRouter({ # (http->django views is added by default) 'websocket': AuthMiddlewareStack( URLRouter( url_pat ), ), }) On localhost all works correctly.