Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
GraphQL multiple queries in one request in Django
Im using Django with graphene to build an API but i want to combine two models in one query, all the fields of the models are the same. Example schema.py import graphene from graphene_django import DjangoObjectType from .models import Post, Post2 class PostType(DjangoObjectType): class Meta: model = Post class Post2Type(DjangoObjectType): class Meta: model = Post2 class Query(graphene.ObjectType): post = graphene.List(PostType) post2 = graphene.List(Post2Type) def resolve_post(self, info): return Post.objects.all() def resolve_post2(self, info): return Post2.objects.all() I get this response: { "data": { "post": [ { "title": "post 1" } ], "post2": [ { "title": "post test" } ] } } What i want to get is: { "data": { "allPost": [ { "title": "post 1" }, { "title": "post test" } } } -
context processor: how to write login and signup in all views
I created a view for Login/Signup/Forget Password (5 forms in single view). I need these forms in header so I added links in base.html and extended in all templates. How can I make this view available for all templates. def master_link(request): login_form = UserLoginForm() send_otp_form = SendOTPForm() verify_otp_form = VerifyOTPForm() registration_form = RegistrationForm() forget_password_form = ForgetPasswordForm() if request.method == 'POST' and 'login_submit' in request.POST: login_form = UserLoginForm(request.POST) if login_form.is_valid(): user = login_form.login(request) if user: login(request, user) return HttpResponseRedirect(reverse('home')) elif request.method == 'POST' and 'send_otp_submit' in request.POST: send_otp_form = SendOTPForm(request.POST) if send_otp_form.is_valid(): mobile_number = send_otp_form.cleaned_data['mobile_number'] type_otp = send_otp_form.cleaned_data['type'] otp = random.randint(1000, 9999) otpobj = sendotp.sendotp.sendotp(settings.AUTH_KEY, str(otp) + ' keep otp with you.') otpobj.send(mobile_number, 'TestOTP', otp) return HttpResponseRedirect(reverse('verify_otp', args=(mobile_number, type_otp))) elif request.method == 'POST' and 'signup_submit' in request.POST: registration_form = RegistrationForm(request.POST) if registration_form.is_valid(): user = registration_form.save(commit=False) mobile_number = registration_form.cleaned_data['mobile_number'] user.username = registration_form.cleaned_data['mobile_number'] password = registration_form.cleaned_data['password'] gender = request.POST.get('inlineRadioOptions') user.gender = gender user.mobile_number = mobile_number user.set_password(password) user.save() new_user = authenticate(username=mobile_number, password=password) login(request, new_user) return HttpResponseRedirect(reverse('home')) elif request.method == 'POST' and 'forget_password_submit' in request.POST: forget_password_form = ForgetPasswordForm(request.POST) if forget_password_form.is_valid(): password = forget_password_form.cleaned_data['password'] mobile_number = forget_password_form.cleaned_data['mobile_number'] user = User.objects.get(mobile_number=mobile_number) user.set_password(password) user.save() return HttpResponseRedirect(reverse('home')) elif request.method == 'POST': verify_otp_form = VerifyOTPForm(request.POST) if verify_otp_form.is_valid(): return HttpResponseRedirect(reverse('home')) # … -
docker-compose cannot wait for mysql database
I am having real problems trying to get a docker-compose script to initiate a mysql database and a Django project, but get the Django project to wait until the mysql database is ready. I have two files, a Dockerfile and a docker-compose.yml, which I have copied below. When I run the docker-compose.yml, and check the logs of the web container, it says that it cannot connect to the database mydb. However the second time that I run it (without clearing the containers and images) it connects properly and the Django app works. I have spent a whole day trying a number of things such as scripts, health checks etc, but I cannot get it to work. Dockerfile FROM python:3.6 ENV PYTHONUNBUFFERED 1 RUN mkdir /code WORKDIR /code COPY ./ /code/ RUN pip install -r requirements.txt RUN python manage.py collectstatic --noinput docker-compose.yml version: '3' services: mydb: environment: - MYSQL_ROOT_PASSWORD=password - MYSQL_USER=django - MYSQL_PASSWORD=secret - MYSQL_DATABASE=dbMarksWebsite image: mysql:5.7 ports: # Map default mysql port 3306 to 3308 on outside so that I can connect # to mysql using workbench localhost with port 3308 - "3308:3306" web: environment: - DJANGO_DEBUG=1 - DOCKER_PASSWORD=secret - DOCKER_USER=django - DOCKER_DB=dbMarksWebsite - DOCKER_HOST=mydb - DOCKER_PORT=3306 build: . command: … -
sqlite3 update conflict with django (Windows10) SQLite 3.8.3 or later is required (found 3.7.17))
I am using Windows 10 and installed django When I navigate into the folder where the manage.py file is an run python manage.py runserver I get the following output SQLite 3.8.3 or later is required (found 3.7.17)) I am using python 3.7.7 and the package for Sqlite installed is 3.31.1. Any ideas how to fix this? Tried to downgrade to django 2.1.2 via pycharm but did not work. -
Automatically attach to parent in nested API
I am trying to create a nested API with DRF with the following structure: projects/visits/activities/items/ projects can have multiple visits each visit has a number of activities each activity contains some items (images with metadata) I used NestedDefaultRouter and registered them after eachother: class NestedDefaultRouter(NestedRouterMixin, DefaultRouter): pass router = NestedDefaultRouter() projects_router = router.register('projects', ProjectViewSet) projects_router.register( 'visits', VisitViewSet, basename='projects-visit', parents_query_lookups=['project__code']).register('activities', AcivityViewSet, basename='projects-visits-activities', parents_query_lookups=['visit__project__code', 'visit__name'] ).register('items', ItemViewSet, basename='projects-visits-activities-items', parents_query_lookups=['item__project__code', 'item__visit__name','item__activity'] ) The goals is to get the following structure working: ENDPOINTS projects/ GET: list all projects projects/ POST: create new project projects// GET show project details projects//visits/ GET list all visits of a project projects//visits/ POST create a new visit projects//visits/ GET show visit details projects//visits/activities/ GET show all activities of certain visit of certain project projects//visits/activities/ POST create new activity of certain visit of certain project projects//visits/activities/ GET show visit details projects//visits/activities//items/ GET show all items of certain activity of certain visit of certain project projects//visits/activities//items/ POST create new item for certain activity projects//visits/activities//items/ GET show item details class Project(models.Model): name = models.CharField(max_length=100, null=True) code = models.CharField(max_length=100, null=True) def __str__(self): return self.name class Visit(models.Model): project = models.ForeignKey(Project, related_name='visits',null=True, on_delete=models.CASCADE) name = models.CharField(max_length=100, null=True) def __str__(self): return self.name class Activity(models.Model): activity = … -
How do I set up a django website with basic backend on Direct Admin?
I am new to website deployment. I have a website with basic backend functionality for sending emails in django. I have purchased a basic DirectAdmin Web Control panel for hosting my website. I was able to set it up for static files of HTML by just simply uploading the files. But how do I go about for dynamic websites, i.e with backend functionality? Do I have to set up an Apache server or so and where do I configure the settings? The Direct Admin dashboard shows options in the GUI such as Apache handlers, MyPHP Admin etc but I am lacking the understanding on how to utilise these features. How do I possibly set up the servers and install the requirements and get it running? Please point me towards good resources for the same as I am absolutely lost. -
Django Making a Dynamic Form
I have a model called forms which can be edited from the admin panel with a list of fields lets say text1, text2, text3, image1, image2, image3. The admin can do in and input values for those lets say text1='First Name', text2='Last Name', text3='Email', image1='Logo', image2='', image3=''. Then I have another model named automation with fields the same fields but the values are what it corresponds to (so in the Form model they are all CharField but in Automation model they have the corresponding field CharField, ImageField, FileField, etc). The goal is to render a form that only displays the fields that actually have a value in Form and that value is the label for the form. So for the example above you would get a form like so: First Name: Last Name: Email: Logo: And the image 2 and image 3 are not rendered because there is no value for those in the Form model. I was able to get this working with the code below: forms.py file def get_automation_form(data): class AutomationForm(forms.ModelForm): class Meta: model = Automation fields = data[0] labels = data[1] return AutomationForm views.py file @login_required def form(request): if request.method == 'GET': nickname = request.GET.get('nickname') elif request.method … -
if statement is not working, it is automatically using else statement
from django.shortcuts import render, redirect from django.http import HttpResponse from django.contrib.auth.models import User, auth def register(request): if request.method == 'POST': first_name = request.POST['first_name'] last_name = request.POST['last_name'] username = request.POST['username'] email = request.POST['email'] password1 = request.POST['password1'] password2 = request.POST['password2'] user = User.objects.create_user(username=username, password=password1,email=email,first_name=first_name,last_name=last_name) user.save() return render(request, 'register.html') else: return HttpResponse('run') -
Is it possible in Django model to update a manually created primary key field using a calculated value during save()
IMPORTANT: NOT FOR Dorks. Dorks please excuse and leave this question alone. Now the question: Is it possible in Django to update the manually created primary key field of a model with a predetermined / calculated value during save()? In the following model, for example: class Port_Berthing(models.Model): doc_number = models.PositiveIntegerField(primary_key=True, unique=True, default=1000, ...) created_on = models.DateField(default=timezone.now, verbose_name='Created on') effective_date = models.DateField(verbose_name='Effective From') berthing_rate = models.DecimalField(max_digits=5, decimal_places=2, ...) will it be possible for me to .get the last doc_number value, increment it by 1 and insert the calculated value in the primary key field doc_number for the new record. And if it is possible, can we do this in the model's save() method? -
Dynamic File Paths with Django 3.x and Graph API
I am complete noob to django and using api's. In the process of doing some research I need to look through a bunch of files to extract some meta data. Originally I planned to copy the data down from onedrive and go through the hassle of deploying a server to expose the data. However the data is currently stored on onedrive, and thought it would be easier to access it with a web app/ console application. I went through the process of creating the sample django/python sample application and am able to run that, and figured out the correct permissions to access the root directory, but am stuck on how to go from that to being able to traverse folders and read/download the interesting files. The option I would like at the moment would be to have employ a file navigation. I saw another example from a long time ago with django, but I am having a hard time following it. Ideally I could make a request to the root drive, get the children and render a page with the list of files and folders with url links to the folder contents. clicking the file would render the meta data … -
Matching id's for different models
I have two models. First one creates a work order, second one creates en entry for it. But when i try to access this entry i get NoReverseMatch error. I know this has something to do with id's being generated on random and not matching each other, but i can't figure out how to solve this (i'm new to coding). here's my urls # Home page re_path(r'^$', views.index, name='index'), # Maintenance page re_path(r'^maint/$', views.maint, name='maint'), # Show all open work orders re_path(r'^maint/orders/$', views.orders, name='orders'), # Show all open work orders re_path(r'^maint/closed_orders/$', views.closed_orders, name='closed_orders'), # Detail page for a single work order re_path(r'^maint/orders/(?P<order_id>\d+)/$', views.order, name='order'), # Page for adding new work orders re_path(r'^new_order/$', views.new_order, name='new_order'), # Page for adding a new entry re_path(r'^new_entry/(?P<order_id>\d+)/$', views.new_entry, name='new_entry'), # Page for editing an entry re_path(r'^edit_entry/(?P<entry_id>\d+)/$', views.edit_entry, name='edit_entry'), models class Order(models.Model): """Maintenance work orders""" date_added = models.DateTimeField(auto_now_add=True) owner = models.ForeignKey(User,on_delete=models.CASCADE) entry_filled = models.BooleanField(default=False) repair_filled = models.BooleanField(default=False) closed = models.BooleanField(default=False) def __str__(self): """return a string representation of the model.""" return str(self.id) class Entry(models.Model): order = models.ForeignKey(Order,on_delete=models.CASCADE) origin = models.CharField(max_length=20) local = models.CharField(max_length=200) descr = models.TextField() date_added = models.DateField(auto_now_add=True) class Meta: verbose_name_plural = 'entries' def __str__(self): return str(self.descr)[:50] +"..." view def edit_entry(request, entry_id): """Edit an existing entry.""" … -
How to delete comment
I'm a Django beginner, how do I delete comment from blocked user. For example if user A blocked user B, I want all the comment in user 'A post in B post' and 'B post in A post' to be deleted. The issue about my code is that when user A block user B, all the comment from user A is deleted from user B post, and also user A comment is deleted from A post, that is not what I want. I want user A comment deleted from user B post and user B comment deleted from user A post. -
Django Oracle cursor call external database view
I established a connection from my Django's project to external a Oracle database, connection it's done successfully and I can call store procedures or functions correctly like this: days = cursor.callfunc('VAC_DICT', cx_Oracle.NUMBER, (identification,)) result = cursor.callproc('PINS_VAC', [data.get('identification'),'true']) Thing is, I need to call a database view there called 'VAC_HIST', but when I try it this way: periods = cursor.execute('VAC_HIST') It gets me "django.db.utils.DatabaseError: ORA-00900: invalid SQL statement", got it, make sense that Im not using the correct syntax, but I searched a lot and can't find how to use cursor. something to call views, like "cursor.callview" or other.... Any idea how or what am I missing ?, thanks in advance. -
How to return query set in SerializerMethodField in Django
if I have SerializerMethodField and I wants to return query set. I tried to do this but doesn’t work available_times = serializers.SerializerMethodField() def get_available_times(self, obj): qs = AvailableTimes.objects.filter(hall__id=obj.id) serializer = AvailableTimesSerializer(qs, read_only=True ,many=True) return serializer.data it not working... give and Error. -
Value comparison query Django
Good afternoon ... I need to make a comparative query ... I implemented this snippet in my view, but it returns me an error ... can someone help me .. Models class Room (models.Model): block = models.ForeignKey (Block, on_delete = models.PROTECT) room = models.CharField ('Room:', unique = True, max_length = 50) capmax = models.IntegerField ('Maximum Cap:') available = models.BooleanField ('Available', default = True) busy = models.BooleanField ('Busy', default = False) internet = models.BooleanField ('Internet', default = False) projector = models.BooleanField ('Projector', default = True) computer = models.BooleanField ('Computer', default = False) class Estclass (models.Model): estclass = models.CharField ('Class', max_length = 20) course = models.CharField ('Course', null = False, max_length = 50) period = models.CharField ('Period', null = False, max_length = 50) discipline = models.CharField ('Discipline', max_length = 50) estudents = models.IntegerField ('Qty') professor = models.CharField ('Professor', max_length = 50) allocated = models.BooleanField ('Allocated', default = False) internet = models.BooleanField ('Internet', default = False) projector = models.BooleanField ('Projector', default = False) computer = models.BooleanField ('Computer', default = False) class Allocate (models.Model): date = models.DateField ('Date', auto_now = True, blank = True) days = [ ('Monday', 'Monday'), ('Tuesday', 'Tuesday'), ('Wednesday', 'Wednesday'), ('Thursday', 'Thursday'), ('Friday', 'Friday'), ('Saturday', 'Saturday'), ] day = models.CharField ('Day', … -
django: Standard form is working but not bootstrap model form
I am working on a note app(clone of Google's keep). When adding a Note using Standard form, it works & a note instance is created on the database but when I am using a bootstrap Model form, then it is not working. Both types of form uses the same action, method, and view as well. Here is the link of the form which I wrote. Note- I have commented out the bootstrap Model form & at the bottom, there is the standard form(it starts from here). And, link of the view file. Also, I know the Ajax way of doing it, but still, I want to know where I am missing when I am doing like this. Or it is not possible to do like this. -
How to increment a manually created primary key field of a Django model using a calculated value during save
Is it possible in Django to update the manually created primary key field of a model with a predetermined / calculated value during save()? In the following model, for example: class Port_Berthing(models.Model): doc_number = models.PositiveIntegerField(primary_key=True, unique=True, default=1000, ...) created_on = models.DateField(default=timezone.now, verbose_name='Created on') effective_date = models.DateField(verbose_name='Effective From') berthing_rate = models.DecimalField(max_digits=5, decimal_places=2, ...) will it be possible for me to .get the last doc_number value, increment it by 1 and insert the calculated value in the primary key field doc_number for the new record. And if it is possible, can we do this in the model's save() method? -
Unable to access list elements in Django Webpage
Following is the context dictionary that I am passing I am rendering to my webpage context = {'subdivision_selected': str(subdivision_selected), 'labels': keep_month_names_only(list(rainfall_data[0].keys())), 'data': new_dict} data = {'2011': [26.9, 84.8, 72.8, 111.4, 326.5, 383.2, 583.2, 441.5, 757.1, 212.3, 150.8, 238.5], '2012': [119.9, 45.6, 30.9, 55.8, 533.9, 458.2, 317.3, 369.6, 868.9, 209.7, 300.5, 187.3], '2013': [67.1, 37.6, 43.0, 46.3, 509.3, 777.0, 564.8, 336.7, 473.6, 455.8, 354.2, 92.3], '2014': [41.9, 8.6, 0.0, 11.1, 238.0, 416.6, 467.6, 321.6, 412.9, 402.6, 201.2, 100.4]} After passing the context I am accessing the same from Django Webpage using chart.js as shown in following code {% for a in data %} var ctx = document.getElementById({{ a }}).getContext('2d'); var myChart = new Chart(ctx, { type: 'line', data: { labels: [{% for i in labels %}"{{ i }}",{% endfor %}], datasets: [{ label: '{{ subdivision_selected }} {{ a }}', data: {{ data.a }}, }] }, }); {% endfor %} When i try to access following line, it returns empty and blank page is seen data: {{ data.a }}, -
How to get list of subscribed queue names in Celery/Django?
My worker is run with: celery worker -A workerTasks -n Worker%h --concurrency=1 --loglevel=info -Q $QUEUE_NAME -f $WORKER_LOG_FILE --pidfile=/logs/worker_pid%h.pid I'm wondering if I can make a python/celery call within the process to find which queue(s) this worker is "subscribed" to? (I do NOT want to find the value of $QUEUE_NAME directly) -
Django - Is there any way to display multiple {% block content %} side by side?
First of all, I'm new to Python/Django in general. The problem I'm facing right now has been itching me for the past day, can't figure out how to make this work. So, I'm trying to create a grid layout (using Bootstrap 4) where I would be able to show Movies/Shows which I have completed watching. The closest I found was a blog tutorial in Python/Django, did help me setup everything, from logging in to creating posts. Now, the website is like a typical blog - everything gets stacked vertically, until it reaches a certain amount of posts, then you see the pagination. What I would like to do, is to display some sort of grid, here's a small example of how it looks now, and what I am trying to create: [ col-md-9 ][ col-md-3 ] In the above example, the {% block content %} and {% endblock %} fill in the col-md-9 section of the site, almost like a container-fluid. Ignore the col-md-3, the blog had it as a sidebar, which I don't really need. What I'm trying to do would need to look something like this: [col-md-3][col-md-3][col-md-3][col-md-3] Not sure how to make the {% block content %} smaller … -
How do I reply to a tweet from my web using following way
I have tweets on my web I need to make reply over a tweet via python script in the following way. As a user, I am on a web page have 10 tweets with a button named reply on each tweet as soon as I click on this button, twitter login page opens and ask for user email and password when I entered correct credential it opens a textarea for replying text with submit button then I write reply text and submit it is replied to that tweet. If I already logged in on twitter the process of login page will be skipped. Any help will be much appreciated -
How to annotate a queryset with the number of hours since creation
I have the following View model: class View(models.Model): # The date/time when this View was created. created_at = models.DateTimeField(default=timezone.now) In my queryset I want to annotate each View object with a hours_since_created field. I have used the following approach: View.objects.annotate(age_in_hours=ExpressionWrapper(Now() - F('created_at'), output_field=IntegerField())) But this sets the age_in_hours field to a really large integer value and I am not exactly sure how I can convert it to hours. Is there anyway where I can add the hours_since_created field as the number of hours that went by since creation? -
how to add object in ArrayReferenceField attribute django (using djongo field)
# Model # class Badge(models.Model): _id = models.CharField(unique=True, default=random_string, editable=False, max_length=100) image = models.ImageField(upload_to=badge_file_path) upload_date = models.DateTimeField(auto_now_add=True) last_update = models.DateTimeField(auto_now_add=True) qr_pos = models.CharField(null=True, blank=True, max_length=100) fill_color = RGBColorField(null=True, blank=True) back_color = RGBColorField(null=True, blank=True) text_pos = models.CharField(null=True, blank=True, max_length=100) text_color = RGBColorField(null=True, blank=True) handle_text = ArrayReferenceField(to=Text, on_delete=models.SET_NULL, blank=True, null=True) View for text_param in text_params: text_pos = list_to_string(text_param["textPos"]) text_color = rgb_to_hex(text_param["textColor"]) key = int(text_param["key"]) text = Text(text_pos=text_pos, text_color=text_color, key=key) print("created") badge.handle_text.append(text) # badge.handle_text.append(text) (raise an error) -
Django shows Realm has no client
I am using django-keycloak package for authenticating users via keycloack, I followed Django keycloack tutorial and while setting up initially after refresh o client it says to refresh certificate at that time I am getting Realm has no client. Also while adding new user using python manage.py keycloack adduser --realm test --user user1 it raises keycloack exception keycloackclientexception not found -
In Django how to display data from current user that's logged in
here am looking for the particular data of logged in user to display in their profile i dont know how to do that please help me with some hint am new here building a django project this is models.py class Loader_post(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, related_name="Loader") pick_up_station = models.CharField(max_length=150) destination_station = models.CharField(max_length=150) sender_name = models.CharField(max_length=150) phone_number = PhoneNumberField(null=False, blank=False, unique=True) receiver_name = models.CharField(max_length=150) sending_item = models.CharField(max_length=150) image_of_load = models.ImageField(default='',upload_to='static/img') weight = models.CharField(max_length=150) metric_unit = models.CharField(max_length=30, default='SOME STRING') quantity = models.PositiveIntegerField() pick_up_time = models.DateField() drop_time = models.DateField() paid_by = models.CharField(max_length=150) created_at = models.DateTimeField(auto_now=True) published_date = models.DateField(blank=True, null=True) def __str__(self): return self.user.username def get_absolute_url(self): return reverse("Loader:post", kwargs={ "username": self.user.username,"pk": self.pk}) this is view.py class Loader_post_list(ListView,SelectRelatedMixin): context_object_name = 'Loader' model = Loader_post template_name = "my_job.html" select_related = ("user") so here is my question that how can i display the data of that loggedin user in their profile after posting the post the data directly display in their profile