Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
how to access multiple models' classes chained with foreign keys in Django
I have 5 models chained with foreign keys in Django (version 3.0.5, Python 3.6.5). Theses models are as follow: class MyUser(AbstractBaseUser, PermissionsMixin): username = models.CharField(_('nick name '), max_length=48, unique=True) first_name = models.CharField(_('First name '), max_length=48) last_name = models.CharField(_('family name '), max_length=48) email = models.EmailField(_(' Emial address'), unique=True) date_joined = models.DateTimeField( _('date_joined'), auto_now=False, auto_now_add=True) date_updated = models.DateTimeField( _('date_updated '), auto_now=True, auto_now_add=False) is_active = models.BooleanField(_('is your account active '), default=True) is_staff = models.BooleanField( _('is the user among admin team '), default=True) avatar = models.ImageField( upload_to='profile_image', blank=True, null=True) class ForumsPosts(models.Model): id = models.AutoField(primary_key=True) user = models.ForeignKey(MyUser, on_delete=models.CASCADE) category = models.ForeignKey(Post_Category, on_delete=models.CASCADE) sub_category = models.ForeignKey(Post_Sub_Category, on_delete=models.CASCADE) title = models.CharField(max_length=64) content = models.TextField(max_length=65536) date_created = models.DateTimeField(auto_now =False, auto_now_add=True) date_updated = models.DateTimeField(auto_now=True, auto_now_add=False) class ForumsPostImages(models.Model): id = models.AutoField(primary_key=True) post = models.ForeignKey(ForumsPosts, on_delete=models.CASCADE) images = models.ImageField(upload_to='ForumsPostimages/%Y/%m/%d', blank=True, null=True ) class ForumsComments(models.Model): id = models.AutoField(primary_key=True) user = models.ForeignKey(MyUser, on_delete=models.CASCADE) post = models.ForeignKey(ForumsPosts, on_delete=models.CASCADE) comment_content = models.TextField(max_length=65536) date_created = models.DateTimeField(auto_now =False, auto_now_add=True) date_updated = models.DateTimeField(auto_now=True, auto_now_add=False) class ForumsCommentImages(models.Model): id = models.AutoField(primary_key=True) comment = models.ForeignKey(ForumsComments, on_delete=models.CASCADE) images = models.ImageField(upload_to='ForumsCommentimages', blank=True, null=True ) I made request using GET method passed through ajax. The GET method has one parameter which is "ForumsPosts ID" . In Django I have a view function as … -
slug field to an existing database and unique slug generator
I already had a database created without the slug field. I wanted to add a unique slug field into my database. I have read the document django document on non nullable unqiue slug and have gone through the video: Master code online. And here is what I have done: I have created a slug field with params max_length and blank=True. Created utils.py in my project folder with function unique_slug_generator. Run python manage.py makemigrations. Added RunPython in migrated file. Run python manage.py migrate. Again changed the slug params to unique=True and repeated the process again. shop/models.py: class products(models.Model): image = models.ImageField(upload_to='products/') name = models.CharField(max_length=50) title = models.CharField(max_length=50) slug = models.SlugField(max_length=150, unique=True) price = models.FloatField() def __str__(self): return self.name project/utils.py: from django.utils.text import slugify import random import string def random_string_generator(size): return ''.join(random.choice(string.ascii_uppercase + string.ascii_lowercase + string.digits) for n in range(size)) def unique_slug_generator(model_instance, name, slug_field): slug = slugify(name) model_class = model_instance.__class__ while model_class.objects.filter(slug=slug).exists(): new_slug = "{slug}-{randstr}".format(slug=slug, randstr=random_string_generator(4) ) return slug After first makemigrations: # Generated by Django 3.0.4 on 2020-04-16 17:41 from django.db import migrations, models from project.utils import unique_slug_generator def update_slug(apps, schema_editor): products = apps.get_model('shop', 'products') for query in products.objects.all(): if not query.slug: query.slug = unique_slug_generator(query, query.title, query.slug) query.save() class Migration(migrations.Migration): dependencies … -
Speed tuning for mysql fetching in Django
I have model like this class MyJson(models.Model): created_at = models.DateTimeField(null=True) tweet_status = JSONField() is_show = models.BooleanField() def __str__(self): return self.tweet_id class Meta: indexes = [ models.Index(fields=['is_show']), models.Index(fields=['created_at',]) ] class MyJsonSerializer(serializers.ModelSerializer): tweet_status = serializers.SerializerMethodField() def get_tweet_status(self,obj): return obj.tweet_status class Meta: model = MyTweet fields = ('id','tweet_status','created_at') class MyJsonFilter(filters.FilterSet): is_show = filters.BooleanFilter(method='is_show_filter') created_at = filters.DateTimeFilter(lookup_expr='gt') def is_show_filter(self, queryset, name, value): return MyJson.objects.filter(is_show=1) then I want to fetch 5000 rows from more than 200000 rows where is_show = 1 order by created_at. But it takes more than 1 min. It's a bit too slow, I want to speed up more.... Where is the bottle neck???or where should I improve?? I set is_show and created_at as index. Is there any setting for this case??? -
Why are my users messages not appearing fully?
Ok, so I am building an inbox and messaging system for my DatingApp. I have been able to display the conversations between my user and other users in my view 'Messages'. Now, I am attempting to display the contents of the conversations through messages via the Message view but I am failing. Because only the sent messages from request.user are showing. I attempted doing two queries at once through my InstantMessage model (which has a foreign key to my Conversation model), a query for request.user and one for user, but still, only the messages sent from request.user are showing up. And furthermore, when you click on the conversation, it should only show messages between that specific user but I am showing ALL messages sent out by request.user to ALL users. So I got two problems here. I'm super stuck on this, so any help would be HIGHLY appreciated. views.py/Message and Messages #Displays contents of a conversation via messages def message(request, profile_id): messages = InstantMessage.objects.filter(Q(sender_id=request.user) | Q(sender_id=profile_id)).\ values('sender_id','receiver_id', 'message', 'date', ).\ order_by('date',) conversations = Conversation.objects.filter(members=request.user) context = {'messages' : messages, 'conversations':conversations} return render(request, 'dating_app/message.html', context) #Displays conversations a user is having def messages(request,profile_id): messages = InstantMessage.objects.filter(Q(sender_id=request.user) | Q(sender_id=profile_id)).\ values('sender_id','receiver_id', 'message', 'date', … -
How can i get error logs on my live Django/Django channels app?
I deployed a Django/Django Channels application to a VPS using Nginx, Gunicorn, Daphne and systemd, everything seems to work for now, but when i try to reach a Websocket consumer of my app using this: ws = create_connection("ws://mydomain/receiver") ws.send('Test') I get a Connection refused error, which means that something is not right on my Django Channels side. Since the Django app is running on a linux VPS, i do not have access to a console like i would during development. Is there any way to check the errors of my application, or a console or anything that would help me see what's happening behind the scenes here? -
Django model that stores multiple other models that store multiple other models
I am learning Django so this is all very new to me. What I am trying to create is a bit of functionality in my admin panel that will allow me to create a layout like this. Test -Event1 --Property1 --Property2 --Property3 --Property4 -Event2 --Property1a --Property2b --Property3c --Property4d -Event3 --Property1aa --Property2bb --Property3cc --Property4dd -Event4 --Property1aaa --Property2bbb --Property3ccc --Property4ddd I want to have multiple tests. My current model setup looks like this: from django.db import models from django.forms import ModelForm TYPE_CHOICES = ( ("string", "string"), ("integer", "integer"), ("array", "array"), ("boolean", "boolean") ) class Test(models.Model): name = models.CharField(max_length=255) description = models.CharField(max_length=255, blank=True) class Meta: verbose_name = 'Test' verbose_name_plural = 'Tests' def __str__(self): return self.name class Event(models.Model): name = models.CharField(max_length=255) test_id = models.IntegerField() class Meta: verbose_name = 'Event' verbose_name_plural = 'Events' def __str__(self): return self.name class Property(models.Model): name = models.CharField(max_length=255) property_type = models.CharField(max_length=20, choices=TYPE_CHOICES) expected_value = models.CharField(max_length=255) class Meta: verbose_name = 'Property' verbose_name_plural = 'Properties' def __str__(self): return self.name class TestForm(ModelForm): class Meta: model = Test fields = ['name', 'description'] I have my admin panel setup so that I can create multiple properties. But then when I go to the "Events" section in my admin panel I can only create events. I want … -
NameError at /contact/ name 'ContactForm' is not defined error:
I am creating a contact page where an email is sent to the user. When I go to access the contact page I run into the error "NameError at /contact/ name 'ContactForm' is not defined" Any idea? Code: def Contact(request): Contact_Form = ContactForm if request.method == 'POST': form = Contact_Form(data=request.POST) if form.is_valid(): contact_name = request.POST.get('contact_name') contact_email = request.POST.get('contact_email') contact_content = request.POST.get('content') template = get_template('/contact_form.txt') context = { 'contact_name' : contact_name, 'contact_email' : contact_email, 'contact_content' : contact_content, } content = template.render(context) email = EmailMessage( "New contact form email", content, "Creative web" + '', ['servwishes@gmail.com'], headers = { 'Reply To': contact_email } ) enter code here email.send() return redirect('blog:success') return render(request, 'users/contact.html', {'form':Contact_Form }) -
Django Rest Framework - ImproperlyConfigured: Could not resolve URL for hyperlinked relationship
Similar to this question, but I do not have namespaces or base-names, so none of the solutions in that question have worked. I have 2 models: Organisation Student A student can belong to an organisation. When I retrieve an organisation, I want a child object in the returned JSON that lists the 'related' students as hyperlinked urls (as per HATEOS). models.py class Organisation(TimeStampedModel): objects = models.Manager() name = models.CharField(max_length=50) def __str__(self): return self.name class Student(TimeStampedModel): objects = models.Manager() first_name = models.CharField(max_length=50) last_name = models.CharField(max_length=50) email = models.EmailField(unique=True) organisation = models.ForeignKey(to=Organisation, on_delete=models.SET_NULL, default=None, null=True, related_name='students') serializers.py class OrganisationSerializer(serializers.ModelSerializer): students = serializers.HyperlinkedRelatedField(many=True, read_only=True, view_name='student-detail', lookup_url_kwarg='organisation_id') class Meta: model = Organisation fields = ('id', 'name','students') class StudentSerializer(serializers.ModelSerializer): class Meta: model = Student fields = '__all__' urls.py from rest_framework import routers from .views import OrganisationViewSet, StudentViewSet from django.conf.urls import url router = routers.DefaultRouter() router.register(r'api/v1/organisations', OrganisationViewSet) router.register(r'api/v1/students', StudentViewSet) urlpatterns = router.urls views.py from .models import Organisation, Student from rest_framework import viewsets, permissions from .serializers import OrganisationSerializer, StudentSerializer # Organisation Viewset class OrganisationViewSet(viewsets.ModelViewSet): queryset = Organisation.objects.all() serializer_class = OrganisationSerializer permission_classes = [ permissions.AllowAny ] # Student Viewset class StudentViewSet(viewsets.ModelViewSet): queryset = Student.objects.all() serializer_class = StudentSerializer permission_classes = [ permissions.AllowAny ] So this should work as this … -
daphne in supervisor not working. How to make it work?
alltime in console browser i see it WebSocket connection to 'ws://(amazon_www...).compute.amazonaws.com/ws/chat_view/43/' failed: Error during WebSocket handshake: Unexpected response code: 404 [program:gunicorn] directory = /home/ubuntu/site command=/home/ubuntu/env/bin/gunicorn --workers 1 --bind unix:/home/ubuntu/site/app.sock djangoshop.wsgi:application autostart=true autorestart=true stopasgroup=true [program:platform_asgi_workers] command=/home/ubuntu/env/bin/python3 /home/ubuntu/site/manage.py runworker channels process_name=asgi_worker%(process_num)s numprocs=1 stdout_logfile=/var/log/worker.log [program:daphne] socket=tcp://localhost:9000 directory = /home/ubuntu/site command=/home/ubuntu/env/bin/daphne -u /run/daphne/daphne%(process_num)d.sock --endpoint fd:ft fd:fileno=0 --access-log - --proxy-headers djangoshop.asgi:application numprocs=1 autostart=true autorestart=true stopasgroup=true stdout_logfile=/var/log/worker.log daphne BACKOFF Exited too quickly (process log may have details) gunicorn RUNNING pid 20882, uptime 0:00:16 platform_asgi_workers:asgi_worker0 BACKOFF Exited too quickly (process log may have details) per 1 sec supervisor out daphne STARTING gunicorn RUNNING pid 20882, uptime 0:00:22 platform_asgi_workers:asgi_worker0 STARTING nginx: upstream app { server wsgiserver:8000; } upstream ws_server { server localhost:9000; } server { listen 80; server_name (my_www).compute.amazonaws.com; client_max_body_size 20M; location / { try_files $uri @proxy_to_app; } location /ws { try_files $uri @proxy_to_ws; } location @proxy_to_ws { proxy_http_version 1.1; proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection "upgrade"; proxy_set_header X-Forwarded-Proto https; proxy_set_header X-Url-Scheme $scheme; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_redirect off; proxy_pass http://ws_server; } location @proxy_to_app { proxy_set_header X-Forwarded-Proto https; proxy_set_header X-Url-Scheme $scheme; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header Host $http_host; proxy_redirect off; proxy_set_header Host $host; proxy_set_header X-Forwarded-Port $server_port; proxy_pass http://app; } location /static/ { alias /home/ubuntu//djaro/site/static_in_dev/; } Gunicorn worked, daphne not, with manage.py … -
Django xhtml2pdf non-editable, read-only pdf?
I've got xhtml2pdf version 0.2.3 working in Django, to output a certificate for a user once a course has been completed. The only issue with it is that the PDF is editable, which means the user could change information on it (name, course name, date, etc.) before printing it out. I couldn't find anything in the docs or my searches that referenced whether or not you can make the PDFs read-only once generated. The view: import io from io import BytesIO from xhtml2pdf import pisa from django.core.files import File from django.template.loader import get_template def generate_course_certificate(earned_credit): template = get_template("reports/course_certificate.html") context = {"earned_credit": earned_credit} html = template.render(context) output = BytesIO() inmemoryfile = io.BytesIO(output.getvalue()) pdf = pisa.pisaDocument(BytesIO(html.encode("UTF-8")), inmemoryfile) earned_credit.proof_of_completion.save( f"{earned_credit.course.name} {earned_credit.pk}.pdf", File(inmemoryfile) ) earned_credit.save() I found it odd that it was editable by default. Is there a way to make it read-only? -
Error message : No DjangoTemplates backend is configured
I'm a pretty old guy who used a little bit Django 5-6 years ago. A friend helped me to develop a small program for my needs and I was very impressed by the flexibility of the tool. After 1 year, no more needs, so I stopped using it. Today, coming back to Django, I spend a day to understand how to reinstall Python and Django on Windows 10 and I tested Django with different old codes I used for learning. I still have the files (code, template, input, and output) but I get an error message. I suppose that this message can come from a change in the syntax (new version ??) or an incomplete installation. For a specialist, it would be maybe easy to solve the problem but for me, it is like to climb Everest. So, if anybody has an idea, I would appreciate a lot. To help, I prepare some information. 1/ - _ code _ errors messages (at running) _ template _ input _ output (I got before) 2/ - _ Installation of Python and Django (commands I used) Thanks a lot for your help ! 1/.....==== ==== code (file : main.py) ==== from django.conf import … -
DigitalOcean: Deploying Dockerized Django/PostgreSQL and pointing to domain
I have been following the Django for Professionals book by William Vincent for a little while. After a few weeks, I've successfully completed my first Dockerized Django/Postgres project. Rather than deploy to Heroku, I'd like to try my hand at a DigitalOcean "one click install" Docker droplet; however, I've been struggling. Steps I've taken to deploy: Created droplet Created SSH key, new user CD'd into a directory to pull my repo $cd home/user/<repo dir> Pulled my repo $git pull <repo> Built the Docker machines docker-compose -f docker-compose-prod.yml up --build -d # dockerfile # pull base image FROM python:3.7 # set environment variables ENV PYTHONDONTWRITEBYTECODE 1 ENV PYTHONUNBUFFERED 1 # set work directory WORKDIR /code # install dependencies COPY Pipfile Pipfile.lock /code/ RUN pip install pipenv && pipenv install --system # copy project COPY . /code/ # docker-compose-prod.yml version: '3.7' services: web: build: . # command: python /code/manage.py runserver 0.0.0.0:8000 command: gunicorn layoffs.wsgi -b 0.0.0.0:8000 environment: - ENVIRONMENT=production - SECRET_KEY=mysecretkey ports: - 8000:8000 depends_on: - db db: image: postgres:11 env_file: - myenv.env Building the Docker containers works, I'm able to do things like create a superuser using docker-compose exec web python manage.py createsuperuser, run migrations, and using docker-compose logs shows that … -
How do I configure my model such that my generated Django migration doesn't result in an error?
I'm using Django and Python 3.7. When I run my command to generate a migration ... (venv) localhost:web davea$ python manage.py makemigrations maps Migrations for 'maps': maps/migrations/0003_auto_20200416_1017.py - Alter field name on cooptype - Alter unique_together for cooptype (0 constraint(s)) The generated migration looks like ... # Generated by Django 2.0 on 2020-04-16 15:17 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('maps', '0002_auto_20200401_1440'), ] operations = [ migrations.AlterField( model_name='cooptype', name='name', field=models.CharField(max_length=200, unique=True), ), migrations.AlterUniqueTogether( name='cooptype', unique_together=set(), ), ] However, running the migration results in an error ... (venv) localhost:web davea$ python manage.py migrate maps System check identified some issues: WARNINGS: ?: (mysql.W002) MySQL Strict Mode is not set for database connection 'default' HINT: MySQL's Strict Mode fixes many data integrity problems in MySQL, such as data truncation upon insertion, by escalating warnings into errors. It is strongly recommended you activate it. See: https://docs.djangoproject.com/en/2.0/ref/databases/#mysql-sql-mode Operations to perform: Apply all migrations: maps Running migrations: Applying maps.0003_auto_20200416_1017...Traceback (most recent call last): File "/Users/davea/Documents/workspace/chicommons/maps/web/venv/lib/python3.7/site-packages/django/db/backends/utils.py", line 85, in _execute return self.cursor.execute(sql, params) File "/Users/davea/Documents/workspace/chicommons/maps/web/venv/lib/python3.7/site-packages/django/db/backends/mysql/base.py", line 71, in execute return self.cursor.execute(query, args) File "/Users/davea/Documents/workspace/chicommons/maps/web/venv/lib/python3.7/site-packages/MySQLdb/cursors.py", line 209, in execute res = self._query(query) File "/Users/davea/Documents/workspace/chicommons/maps/web/venv/lib/python3.7/site-packages/MySQLdb/cursors.py", line 315, in _query db.query(q) File "/Users/davea/Documents/workspace/chicommons/maps/web/venv/lib/python3.7/site-packages/MySQLdb/connections.py", line 239, in … -
Is there any issue about installation of Django?
enter image description here Hello all ,I am creating my very first project in django using VS code editor its very basic but giving error unexpected indent pylint error -
Sidebar content list is coming below profile image in django webpage bootstrap 4
Everything was right until I used profile pic in webpage. The sidebar content which was on the right of webpage is now coming below profile pic. If I use float-right it comes to the right but still below profile pic. I'm using sublime 3 for this django project. My code for profile pic is- {% extends "blog/base.html" %} {% load crispy_forms_tags %} {% block content %} <div class="content-section"> <div class="media"> <img class="rounded-circle" width="100px" src="{{ user.profile.image.url }}"> <div class="media-body"> <h2 class="account-heading">{{ user.username }}</h2> <p class="text-secondary">{{ user.email }}</p> </div> </div> <!-- FORM HERE --> </div {% endblock content %} And that for sidebar content is- <div class="col-md-4"> <div class="content-section"> <h3>Our Sidebar</h3> <p class='text-muted'>You can put any information here you'd like. <ul class="list-group"> <li class="list-group-item list-group-item-light">Latest Posts</li> <li class="list-group-item list-group-item-light">Announcements</li> <li class="list-group-item list-group-item-light">Calendars</li> <li class="list-group-item list-group-item-light">etc.</li> </ul> </p> </div> </div> And my webpage actually looks like this- "PROF username ILE email PIC" Sidebar content Sorry I couldn't upload image -
What is the purpose of app_name in urls.py in Django?
When include()ing urlconf from the Django app to the project's urls.py, some kind of app's name (or namespace) should be specified as: app_namespace in include((pattern_list, app_namespace), namespace=None) in main urls.py or app_name variable in app's urls.py. Since, I guess, Django 2, the second method is the preferred one Although I copy-pasted first function signature from Django 3 documentation. But that's not the main point. My current understanding of namespace parameter of include() is that it's what I use when using reverse(). What is the purpose of app_name in app's urls.py or app_namespace in main urls.py? Are these exactly the same thing? How is it used by Django? Existing questions (and answers) I've found here explain HOW I should specify it rather than WHY. -
Create auto increment number for every user when ordering
This is the most asked question, but I am failing to accomplish this task. I have a Book model with book_history field like class Book(Models): customer = models.ForeignKey(Customer) book_history_number = models.CharField(max_length=120) def _get_book_customer_id(self): b_id = self.customer num = 1 while Book.objects.filter(customer=b_id).exists(): num += 1 return cus_ord_id def save(self, *args, **kwargs): if not self.book_history_number: self.book_history_number = self._get_book_customer_id() my objective is to increment by when a user book something for example I have A and B users and A booked smth and book_history_number should be 1 next time it should 2 like this: A: 1, 2,... n because A booked two times B: 0 B did not booked but if B user did it would be 1. with above code I cannot able to solve this problem. Any help please -
How can I move my django project to another directory?
There have been questions asked about similar things, but over 4 years ago. I'm sure those things don't apply because I have tried them and they didn't work. I was working in a directory where I had my virtualvenv and django project but I wanted to create a new folder and move them to that new folder: old path: dev/python/django/ new path: dev/python/django/blog I then activated my virtualenv and moved into the directory where the manage.py file was and, as I always have, ran python manage.py runserver however it shot out an error: File "manage.py", line 16 ) from exc ^ SyntaxError: invalid syntax I haven't changed anything in my manage.py file, in fact, I didn't change anything since the last time I ran this project. Since I moved the project and the virtualenv attached to it, it no longer runs. I tried reinstalling django in my env, but it says it already exists. I tried running python3 manage.py runserver as some other posts suggest, but that doesn't work either. Same error... What am I missing? All of the paths in my files are from the BASE_DIR variable and no paths are absolute. What am I missing? How can I … -
Problems of object grabbing
I want to add course.tutor.add(self.request.user) to the function below but don't know how to do that, because i don't know how to do without slug and so on class FormWizardView(SessionWizardView): template_name = 'courses/create_course.html' file_storage = FileSystemStorage(location=os.path.join(settings.MEDIA_ROOT,'courses')) form_list = (CourseForm1,CourseForm2,CourseForm3,CourseForm4) def done(self, form_list, **kwargs): instance = Course() for form in form_list: for field, value in form.cleaned_data.items(): setattr(instance, field, value) instance.save() return redirect('courses:my_courses',username=self.request.user.username) -
How to add request.session/user data to Postman POST?
A web request POST has request.user and request.session as the follows that was logged on server. It's easy to add parameters and body etc. How to add the request.session/user data (or simulate ?) to Postman POST? request.user: { id: 1061, username: jhon, name: 'jhon, smith' } request.session: {'case_id': 777, 'profile_id': u'101'} -
Connecting Serializers in Django 'int' object has no attribute 'split'
This is the first time I started working with APIs in Django, and I'm building a web app that processes a lot of changes very quickly. After much research, I decided to use serpy instead of the DRF for the serializers, but I'm having trouble connecting multiple serializers. I don't think this is a serpy issue, but just a general lack of knowledge of working with serializers in general. I have a Membership model and a Project model, and when I request the Project model, I want to see the active Memberships associated with that project. Pretty simple stuff right. Here are my serializers: ###################################################### # Memberships ###################################################### class MembershipSerializer(LightWeightSerializer): id = Field() user = Field(attr="user_id") project = Field(attr="project_id") role = Field(attr="role_id") is_admin = Field() created_at = Field() user_order = Field() role_name = MethodField() full_name = MethodField() is_user_active = MethodField() color = MethodField() photo = MethodField() project_name = MethodField() project_slug = MethodField() is_owner = MethodField() def get_photo(self, obj): return get_photo_url(obj['photo']) def get_role_name(self, obj): return obj.role.name if obj.role else None def get_full_name(self, obj): return obj.user.get_full_name() if obj.user else None def get_is_user_active(self, obj): return obj.user.is_active if obj.user else False def get_color(self, obj): return obj.user.color if obj.user else None def get_project_name(self, obj): return … -
No reverse match error on redirect (django)
I encountered a NoReverseMatch at /login Reverse for '' not found. '' is not a valid view function or pattern name. template <form action="" method="post"> {% csrf_token %} <input type="text" name="username" placeholder="Username"><br> <input type="password" name="password" placeholder="Password"><br> <input type="submit"> </form> views.py def loginuser(request): if request.method == 'POST': username = request.POST['username'] password = request.POST['password'] user = auth.authenticate(username = username,password=password) if user is not None: auth.login(request, user) return redirect(request,'home') else: messages.info(request,'Invalid username or password') return render(request,'login.html') urls.py from django.urls import path from accounts import views urlpatterns = [ path('', views.signup, name='signup'), path('login',views.loginuser,name='login'), path('logout',views.logout,name='logout'), path('home', views.home, name='home'), ] -
back-end architecture to integrate with Cube.js
I'm looking for advise choosing a back-end architecture for a web app. In the app, users upload tabular data from multiple files. Their data is then processed, aggregated and visualized. Data is private and each user has their own dashboard. I believe Cube.js is an excellent choice for the dashboard, but I am wondering what back-end web framework I should integrate it with. I have experience of Django, but would use Express if it had significant advantages. Thanks for any advice! -
I am getting the error below every time I run the code and I do not know what is wrong
I am getting the error below. Any help is appreciated. I am probably missing something very important from the documentation. Kindly point out my mistake if you see it and enlighten me about many to many relations from Django. From the error presented does it mean that the .add() function cannot be used on querysets? Traceback Internal Server Error: /7/ Traceback (most recent call last): File "C:\Users\hanya\AppData\Local\Programs\Python\Python37\lib\site-packages\django\core\handlers\exception.py", line 34, in inner response = get_response(request) File "C:\Users\hanya\AppData\Local\Programs\Python\Python37\lib\site-packages\django\core\handlers\base.py", line 126, in _get_response response = self.process_exception_by_middleware(e, request) File "C:\Users\hanya\AppData\Local\Programs\Python\Python37\lib\site-packages\django\core\handlers\base.py", line 124, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\music\songs\views.py", line 141, in Playlist_Add playlist.song.add(song) File "C:\Users\hanya\AppData\Local\Programs\Python\Python37\lib\site-packages\django\db\models\fields\related_descriptors.py", line 926, in add self._add_items(self.source_field_name, self.target_field_name, *objs) File "C:\Users\hanya\AppData\Local\Programs\Python\Python37\lib\site-packages\django\db\models\fields\related_descriptors.py", line 1073, in _add_items '%s__in' % target_field_name: new_ids, File "C:\Users\hanya\AppData\Local\Programs\Python\Python37\lib\site-packages\django\db\models\query.py", line 844, in filter return self._filter_or_exclude(False, *args, **kwargs) File "C:\Users\hanya\AppData\Local\Programs\Python\Python37\lib\site-packages\django\db\models\query.py", line 862, in _filter_or_exclude clone.query.add_q(Q(*args, **kwargs)) File "C:\Users\hanya\AppData\Local\Programs\Python\Python37\lib\site-packages\django\db\models\sql\query.py", line 1263, in add_q clause, _ = self._add_q(q_object, self.used_aliases) File "C:\Users\hanya\AppData\Local\Programs\Python\Python37\lib\site-packages\django\db\models\sql\query.py", line 1287, in _add_q split_subq=split_subq, File "C:\Users\hanya\AppData\Local\Programs\Python\Python37\lib\site-packages\django\db\models\sql\query.py", line 1225, in build_filter condition = self.build_lookup(lookups, col, value) File "C:\Users\hanya\AppData\Local\Programs\Python\Python37\lib\site-packages\django\db\models\sql\query.py", line 1096, in build_lookup lookup = lookup_class(lhs, rhs) File "C:\Users\hanya\AppData\Local\Programs\Python\Python37\lib\site-packages\django\db\models\lookups.py", line 20, in __init__ self.rhs = self.get_prep_lookup() File "C:\Users\hanya\AppData\Local\Programs\Python\Python37\lib\site-packages\django\db\models\fields\related_lookups.py", line 59, in get_prep_lookup self.rhs = [target_field.get_prep_value(v) for v in self.rhs] … -
How to get primary key of recently created record in django not the latest one
id = request.session['user-id'] Forum.objects.create(user_id=id, forum_name=self.name,tags=self.tags, description=self.desc,reply=0,status=0) Tags.objects.create(forum_id='?', tag=self.tags) How to get forum_id from recently created Forum object not the latest one forum_id?