Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Apache server not starting on WAMP after editing httpd.conf
I installed wamp server on windows and started it. 2 services Apache and MariaDB were runnig successfully but after editing the httpd.conf file to deploy the Django based app the Apache stopped. Then I removed the changes(left the httpd.conf as usual) and found that it started as earlier. So why the Apache stopped after changing the httpd.conf? -
django: convert unsalted md5 (without salt) hash to pbkdf2
I have an old database where user passwords were hashed with md5 without salt. Now I am converting the project into django and need to update passwords without asking users to log in. I wrote this hasher: from django.contrib.auth.hashers import PBKDF2PasswordHasher class PBKDF2WrappedMD5PasswordHasher(PBKDF2PasswordHasher): algorithm = 'pbkdf2_wrapped_md5' def encode_md5_hash(self, md5_hash, salt): return super().encode(md5_hash, salt) and converting password like: for data in old_user_data: hasher = PBKDF2WrappedMD5PasswordHasher() random_salt = get_random_string(length=8) # data['password'] is e.g. '972131D979FF69F96DDFCC7AE3769B31' user.password = hasher.encode_md5_hash(data['password'], random_salt) but I can't login with my test-user. any ideas? :/ -
Giving dropdown list options from another application in django
I Have different applications in django: project usermaster ProjectUserXref--> In this I want to take drop down list of project values from 'project' appplication and drop down list of users from 'User' application and allow user to map available projects to available users. I have two different tables called Project and UserMaster in which I have list of Projects and list of Users respectively. None of them is connected by foreign key as of now. class Project(models.Model): JIRAID = models.CharField(max_length=20,null=True) projectID = models.AutoField(primary_key=True) projectName = models.CharField(max_length=100) projectDescription = models.CharField(max_length=100) projectStartDate = models.DateField() projectEndDate = models.DateField() projectEstimatedLOE = models.IntegerField() createdBy = models.CharField(max_length=30) createdAt = models.DateTimeField(default=datetime.datetime.now,null=True,blank=True) updatedAt = models.DateTimeField(default=datetime.datetime.now,null=True,blank=True) class UserMaster(models.Model): userID = models.AutoField(primary_key=True) userName = models.CharField(max_length=100) domainID = models.CharField(max_length=30) Department = models.CharField(max_length=30) Role = models.CharField(max_length=30) createdBy= models.CharField(max_length=10) createdAt = models.DateTimeField(default=datetime.datetime.now, null=True, blank=True) updatedAt = models.DateTimeField(default=datetime.datetime.now, null=True, blank=True) class ProjectUserXref(models.Model): projectID = models.IntegerField() projectName = models.CharField(max_length=50) userID = models.IntegerField() domainID = models.CharField(max_length=30) createdBy = models.CharField(max_length=30) createdAt = models.DateTimeField(default=datetime.datetime.now, null=True, blank=True) updatedAt = models.DateTimeField(default=datetime.datetime.now, null=True, blank=True) In 'projectID' and 'projectName' column of 'ProjectUserXref' table I should get values from 'projectID' and 'projectName' column of 'Project' table respectively. and 'userID' and 'domainID' column values should get from 'userID' and 'domainID' from 'UserMaster' table. -
Uploading a Django project on Heroku Server
I am new to using the Heroku Server, I uploaded my Django project to Hero and I get this error message on the browser as shown on the screenshot But when I check the log on the admin I see this message below 2019-05-14T21:26:26.138333+00:00 app[web.1]: bash: gunicorn: command not found Please I need help on how to fix this, someone have this issue, but I don't understand the solutions as provided. -
class 'Device' can not find in module.py
/* django from django.db import models class Device(models.Model): ip_address = models.CharField(max_length=255) hostname = models.CharField(max_length=255) username = models.CharField(max_length=255) password = models.CharField(max_length=255) ssh_port = models.IntegerField(default=22) Device = models.CharField(max_length=255) VENDOR_CHOICES = ( ('mikrotik', 'Mikrotik'), ('cisco', 'Cisco') ) vendor = models.CharField(max_length=255, choices=VENDOR_CHOICES) def __str__(self): return "{}. {}".format(self.hostname, self.ip_address) */ from django.shortcuts import render, HttpResponse from .models import Device def home(request): all_device = Device.objects.all() cisco_device = Device.objects.filter(vendor="cisco") mikrotik_device = Device.objects.filter(vendor="mikrotik") context = { 'all_device': len(all_device), 'cisco_device': len(cisco_device), 'mikrotik_device': len(mikrotik_device) } return render(request, 'home.html', context) */ -
Django. Pros and Cons of keeping variable in a class when using GET method then POST method
I've made a Class inherited TemplateView class TEST(TemplateView): url = None def get(self, request, *args, **kwargs): self.url = 'test' return super(TEST, self).get(request, *args, **kwargs) def post(self, request, *args, **kwargs): logging.info(self.url) when I visit a url routing to TEST class, TEST class has variable url with 'test' and when I submit a form with POST, I can get the url from self.url which was set in get function. Are there cons keeping class's variable in this way? Or Is there a possibility to lost the variable 'url' in TEST class? -
access other models through serializer
i have to serialize the object that is not form the model i have two models Occurrence and OccurrenceResponse and querset object is of Occurence model and i want to serialize the value from OccurrenceResponse i have used select_Related and prefetch_related but not able to access it . class OccurrenceResponse(Timestampable, Seeable): tracker = FieldTracker(fields=['response']) objects = OccurrenceResponseManager() RESPONSE_CHOICES = [(choice.identifier, choice.name) for choice in ResponseChoices] occurrence = models.ForeignKey( 'events.Occurrence', verbose_name=_('occurrence'), on_delete=models.CASCADE, ) event_invitation = models.ForeignKey( 'events.EventInvitation', verbose_name=_('event_invitation'), on_delete=models.CASCADE, ) class Occurrence(Timestampable, ChangelogMixin): """ Occurrence of an event """ tracker = FieldTracker(fields=[ 'invite_parents', 'invite_members', 'invite_admins', 'deleted', 'cancelled', 'start', 'meetup_time' ]) objects: ManagerT['Occurrence'] = OccurrenceManager() uuid = models.AutoField(primary_key=True) id = models.BigIntegerField(db_index=True) event = models.ForeignKey( 'events.Event', on_delete=models.CASCADE, related_name='occurrences', verbose_name=_("event") ) class EventInvitation(Timestampable, Seeable): event = models.ForeignKey( 'events.Event', verbose_name=_('event'), on_delete=models.CASCADE, ) user = models.ForeignKey( 'users.User', verbose_name=_('attender'), on_delete=models.CASCADE, ) i want to access occurrence.event_invitation.user how can i do that? -
checkbox widget not displayed after ajax call in a form by Ajax
I call a form by ajax. In this form, this is a part with a checkbox list. The django widget forms.ModelMultipleChoiceField(queryset= ..., widget=forms.CheckboxSelectMultiple, required=False) not displayed class AnswerForm(forms.ModelForm): skills = forms.ModelMultipleChoiceField(queryset= Skill.objects.filter(subject_id = 1), widget=forms.CheckboxSelectMultiple, required=False) waitings = forms.ModelMultipleChoiceField(queryset= Waiting.objects.filter(theme__subject_id = 1).order_by("theme"), widget=forms.CheckboxSelectMultiple, required=False) knowledges = forms.ModelMultipleChoiceField(queryset= Knowledge.objects.filter(theme__subject_id = 1 ).order_by("-level").order_by("theme"), widget=forms.CheckboxSelectMultiple, required=False) class Meta: model = Answer fields = '__all__' def ajax_create_answer(request): id_model = int(request.POST.get('id_model')) data = {} form_ans = inlineformset_factory( Item , Answer , fields=('content','right', 'skills','waitings','knowledges',) , extra= 4 ) print(form_ans) template = 'learning/show_vf_multiples.html' html = render_to_string(template, context ) data['html'] = html return JsonResponse(data) I want the checkbox lists on my form not the default select. Thanks. -
django cronjob is run multiple times
I have multiple cronjob in Django. The default behavior is to prevent multiple runs of same job. But after one month I had lots of cronjobs running. Why is this happening? -
Sending JSON response in chunks in Django
I'm new to Django, basically i have a large JSON that i want to stream in chunks to the Angular app running in client browser. How can this be done? -
how to get a foreignkey object to display full object in django rest framework
I have a django backend built with django_rest_framework. I currently have an object that is a foreign key. when i make a api request to grab an object it displays the foreignkey id and only the id. I want it to display the entire object rather than just the id of the foriegnkey.. Not sure how to do it because it did not really show how to do it in the documentation... here is the code: views page: from users.models import Profile from ..serializers import ProfileSerializer from rest_framework import viewsets class ProfileViewSet(viewsets.ModelViewSet): queryset = Profile.objects.all() lookup_field = 'user__username' serializer_class = ProfileSerializer there is a user foreign key referring to the user urls: from users.api.views.profileViews import ProfileViewSet from rest_framework.routers import DefaultRouter router = DefaultRouter() router.register(r'', ProfileViewSet, base_name='profile') urlpatterns = router.urls Here is the serializer: class ProfileSerializer(serializers.ModelSerializer): class Meta: model = Profile fields = ( 'id', 'user', 'synapse', 'bio', 'profile_pic', 'facebook', 'twitter' ) this is what it looks like: HTTP 200 OK Allow: GET, POST, HEAD, OPTIONS Content-Type: application/json Vary: Accept [ { "id": 1, "user": 3, "bio": "software engineer", "profile_pic": "http://127.0.0.1:8000/api/user/profile/profile_pics/allsum-logo-1.png", "facebook": "http://www.facebook.com/", "twitter": "http://www.twitter.com/" } ] -
Django Rest for Docker communication
I have two docker services, server and worker, and I would like them to communicate via rest calls over Django, is this good practice? Could you provide a minimal example where server sends a command string to worker:8000 ( worker exposes 8000) and worker's django receives it and executes it via os.system(command)? -
Searching based on one column in django
I have one application in django named 'Project'. Basic task is I should be able to create, search and modify projects. Creation page is working fine. On search page, I have given drop down list of existing created projects from database. Now if I select one value from drop down list, It should give me whole row associated with that searched column in editable format so that i can modify the same. I have three files: models.py views.py and .html files for displaying forms models.py: class Project(models.Model): JIRAID = models.CharField(max_length=20,null=True) projectID = models.AutoField(primary_key=True) projectName = models.CharField(max_length=100) projectDescription = models.CharField(max_length=100) projectStartDate = models.DateField() projectEndDate = models.DateField() projectEstimatedLOE = models.IntegerField() createdBy = models.CharField(max_length=30) createdAt = models.DateTimeField(default=datetime.datetime.now,null=True,blank=True) updatedAt = models.DateTimeField(default=datetime.datetime.now,null=True,blank=True) View.py: def projectcreation(request): context = {'form': Project} if request.method=='POST': form = ProjectCreationForm(request.POST) if form.is_valid(): JIRAID=request.POST.get('JIRAID') projectID=request.POST.get('projectID') projectName=request.POST.get('projectName') projectDescription=request.POST.get('projectDescription') projectStartDate=request.POST.get('projectStartDate') projectEndDate=request.POST.get('projectEndDate') projectEstimatedLOE=request.POST.get('projectEstimatedLOE') createdBy=User.objects.get(username=request.user.username) form.save() return render(request,'projectpages/projectcreateconfirmation.html') else: return render(request,'projectpages/projectcreate.html') else: return render(request,'projectpages/projectcreate.html',context) def projectsearch(request): projectid_list = Project.objects.filter(createdBy=request.user.username) return render(request,'projectpages/projectsearch.html',{'projectcreation':projectid_list}) def projectmodification(request): projectid_list = Project.objects.filter(createdBy=request.user.username) return render(request, 'projectpages/projectmodification.html', {'projectcreation': projectid_list}) If i select one value from drop down list from search page , i should get whole row associated with that value on modification page in editable format. -
Cant provide secure connection or Django site
I tried using the following tutorial to serve my django project with apache2 and ssl. https://www.digitalocean.com/community/tutorials/how-to-create-a-self-signed-ssl-certificate-for-apache-in-ubuntu-18-04 I learned how to get apache2 and django successfully working from this tutorial. https://www.digitalocean.com/community/tutorials/how-to-serve-django-applications-with-apache-and-mod_wsgi-on-ubuntu-14-04#configure-apache But, when trying to enable the site for https I get "This site can’t provide a secure connection". Below is my /etc/apache2/sites-available/000-default.conf with comments sections removed. Thank you. <VirtualHost *:80> ServerName 215.65.11.220 ServerAdmin milton.centeno.civ@mail.mil DocumentRoot /var/www/html Redirect permanent / https://215.65.11.220 ErrorLog ${APACHE_LOG_DIR}/error.log CustomLog ${APACHE_LOG_DIR}/access.log combined Alias /static /home/sgoodman/insta/static <Directory /home/sgoodman/insta/static> Require all granted </Directory> <Directory /home/sgoodman/insta/insta_project> <Files wsgi.py> Require all granted </Files> </Directory> WSGIDaemonProcess insta python-path=/home/sgoodman/insta python-home=/home/sgoodman/.local/share/virtualenvs$ WSGIProcessGroup insta WSGIScriptAlias / /home/sgoodman/insta/insta_project/wsgi.py </VirtualHost> -
Getting 'No such object' error when trying to download gcloud app engine builds
I have a Django application running on google app engine. Just because I don't know how to use Git, I usually download latest app engine version from google cloud build and work with different folder names. However this last week, when I try to download my google app engine project, I get this following error: No such object: staging.project-id.appspot.com/eu.gcr.io/project-id/appengine/default.datetime:latest I know I can get my files from cloud shell but I couldn't do it. Thats how I have found cloud builds after searching it for like a week. Note: My Django app is still running. -
django | css | html - As soon as the text is displayed in the browser, the order is not correct any more
I have a problem where I can't find a solution: if i omit the text line (with article.text), the browser displays the order correctly. as soon as i add the text, there is only one in the upper bar, while the remaining three are at the bottom. Here the code with the text: <section id="services"> {% if articles %} {% for article in articles %} <article class="services_article"> <p><img src="{{ article.thumbnail.url }}" alt="Services"></p> <p class="title">{{ article.title }}</p> <p>{{ article.text|safe_markdown|truncatewords:50 }}<a href="{{ article.get_absolute_url }}"> mehr</a></p> </article> {% endfor %} {% endif %} </section> Here the code without the text: <section id="services"> {% if articles %} {% for article in articles %} <article class="services_article"> <p><img src="{{ article.thumbnail.url }}" alt="Services"></p> <p class="title">{{ article.title }}</p> </article> {% endfor %} {% endif %} </section> Here is the css: #services { display: flex; flex-direction: row; flex-wrap: wrap; justify-content: center; } .services_article { text-align: center; max-width: 31.33%; display: inline-table; } -
I need to get the current logged user in the django form , please help ASAP
I am making a blog website , which each user cannot post more than 3 blogs so I wrote that in the form.py file so it can validate the number of blogs before submitting Expected Result : By the fourth blog submission of the same logged user , "You have exceeded limit." this error must appear Actual :'BlogForm' object has no attribute 'request' this error appear -
how to store values in list to more than one variable ( in python django )
I have some list values like ..test_list = ["grandfathers", "name", "is","John"] I want to put all the index value before "is" to one variable ...and store all index values after "is" to another variable for an example , value1 = "grandfathers name" value2 = "John" the index position of "is sometime change , and total number of index in test_list also not always same , so I need a solution which applicable in any situation. -
Dropdown List Foreign Key Django
Good day. I have something to ask. I have Student Model and in that student model i have foreign key Address, What im asking is i want to create a dropdown list from foreign key Address in seperate dropdown list except zip_code like the picture below: Student(models.Model): ... .... Address = models.Foreignkey(Address) Address(models.Model): zip_code = models.CharField(...) city = model.Charfield(..) province= model.Charfield(..) country= model.Charfield(..) Thank you.enter image description here -
Upload and Download using onedrive business at same time with multiple simultaneous request takes much time
I want to convert my docx to pdf using onedrive, so i uploaded my docx in onedrive and download it on same function. I am using python django webserver. def myfunctionname(token,filecontent): headers = {"Content-Type": "text/plain"} txt = fileContent graph_client = OAuth2Session(token=token) drive_url = "mywholeurl" upload = graph_client.put(drive_url, data=txt, headers=headers) download = graph_client.get(drive_url + '?format=pdf') return download.url It took me 5 seconds to upload and download for one request but when i do 20 requests at same time to complete all requests it took around 40 seconds, for 50 concurrent requests it took me around 80 seconds. I was expecting to get all results in same 5 seconds for any number of requests. Can you explain where i am doing wrong? -
UnboundLocalError at /detail/1/ local variable 'post' referenced before assignment
hello please help me i get error in django UnboundLocalError at /detail/1/ local variable 'post' referenced before assignment Request Method: GET Request URL: http://127.0.0.1:8000/detail/1/ Django Version: 2.2.1 Exception Type: UnboundLocalError Exception Value: local variable 'post' referenced before assignment from django.shortcuts import render, get_object_or_404 from .models import post def home (request) : context = { 'titel': 'homepage', 'posts': post.objects.all() } return render (request, 'site.html', context) def post_detail(request, post_id): post = get_object_or_404(post,id=post_id) context = { 'title': post, 'post': post, } -
Passing data from PostgreSQL to frontend without ORM
I'm working on a web application but as I'm pretty green I'd appreciate some advice on some missing pieces from the stack. This is mostly about what is still missing, from my choices of PostgreSQL database, some existing python codes (including psycopg2 as the DB adaptor), and Django framework, to make the whole flow work. Here's the supposed work flow: User uploads raw files via browser (some background information about this type of files is summarized here). In short, the file contains signals and the signals can be wildly named and even the number of signals in each uploaded file is often different. When handling the uploaded file, the server-end will parse the signals and save them to a new data table for each file uploaded, where each column is one signal and the first column is the timestamps for all signals (we're assuming the numbers of points for all signals are same and match the timestamps). At this step a script will also save some meta information about the uploaded file to a master table whose columns include, among other things, 1) the name of the data table, and 2) an array of signal names - this is essentially … -
I tried to implement an image slide using carousel, but it does not work. I wonder why
I tried to implement an image slide using carousel, but it does not work. I wonder why References: https://www.w3schools.com/bootstrap4/tryit.asp?filename=trybs_carousel Is the loop incorrect? I want to print images in image list using Django template syntax and carousel How do I fix it? code: {% extends "layout.html" %} {%block title %}css challenge{% endblock %} {%block extra_css %} .carousel-inner img { width: 100%; height: 100%; } {% endblock %} {% block content %} <div class="container mt-3"> <h2>Carousel</h2> <div id="myCarousel" class="carousel slide" data-ride="carousel"> <!-- Indicators --> <ul class="carousel-indicators"> <li data-target="#myCarousel" data-slide-to="0" class="active"></li> <li data-target="#myCarousel" data-slide-to="1"></li> <li data-target="#myCarousel" data-slide-to="2"></li> </ul> <!-- The slideshow --> <!-- <div class="carousel-inner"> <div class="carousel-item active"> <img src="https://picsum.photos/700/300/?random" alt="Los Angeles" width="1100" height="500"> </div> <div class="carousel-item"> <img src="https://picsum.photos/700/300/?random" alt="Chicago" width="1100" height="500"> </div> <div class="carousel-item"> <img src="https://picsum.photos/700/300/?random" alt="New York" width="1100" height="500"> </div> </div> --> <div class="carousel-inner"> <div class="carousel-item active"> {% for p in object_list %} <div class="carousel-item active"> <img src="{{ p.head_image.url }}"> </div> {% endfor %} </div> </div> <!-- Left and right controls --> <a class="carousel-control-prev" href="#myCarousel" data-slide="prev"> <span class="carousel-control-prev-icon"></span> </a> <a class="carousel-control-next" href="#myCarousel" data-slide="next"> <span class="carousel-control-next-icon"></span> </a> </div> </div> <br><br> {% endblock %} import css <link rel="stylesheet" href="{% static 'blog/bootstrap/bootstrap.css' %}" media="screen"> <link rel="stylesheet" href="{% static 'blog/_assets/css/custom.min.css' %}"> import js <script … -
Display all from queryset rather than only one element
I am trying to display all item from my queryset at the moment it is only displaying one Below is my code that is returning only the first element from my queryset specail_list: views.py try: try: specail_list = Special.objects.get(promotion=True, sp_code=promocode, start__lte=date_instance, minimum_stay__lte=nights, object_id=room_filter.id, end__gte=date_instance, is_active=True, member_deal=False) is_promo=True except: specail_list = Special.objects.filter(promotion=False, start__lte=date_instance, minimum_stay__lte=nights, object_id=room_filter.id, end__gte=date_instance, is_active=True, member_deal=False)[0] specail_list2 = Special.objects.filter(promotion=False, start__lte=date_instance, minimum_stay__lte=nights, object_id=room_filter.id, end__gte=date_instance, is_active=True, member_deal=False) is_promo=False min_stay_check_end = chek_in + datetime.timedelta(days=specail_list.minimum_stay - 1) min_stay_check_start = check_out - datetime.timedelta(days=specail_list.minimum_stay) if min_stay_check_end > (specail_list.end.date() + datetime.timedelta(days=1)) and (check_out + datetime.timedelta(days=1)) > specail_list.end.date(): specail_list = None if min_stay_check_start < (specail_list.start.date() + datetime.timedelta(days=1)) and (chek_in < specail_list.start.date() + datetime.timedelta(days=1)): specail_list = None except: specail_list=None try: if specail_list.discount_type =="NIGHTS": if specials_nights < (specail_list.minimum_stay * int(nights/specail_list.minimum_stay)): discount = specail_list.nights_off_discount(Decimal(cost_of_rooms)) print(discount) specials_nights += 1 else: discount = 0 elif specail_list.discount_type =="FLAT": discount = Decimal(specail_list.pay_days) else: discount = specail_list.discount(1,Decimal(cost_of_rooms),adults,children,no_of_rooms) cost_of_rooms = Decimal(cost_of_rooms)-Decimal(discount) price_instance= math.ceil((Decimal(price_instance) * Decimal(ex.rate))*100)/100 cost_of_rooms = math.ceil((Decimal(cost_of_rooms) * Decimal(ex.rate))*100)/100 discount_recived =Decimal(price_instance)-Decimal(cost_of_rooms) newli.append({'room': room_instance, 'display_order':room_filter.display_order, 'rm': room_filter, 'date': date_instance, 'quantity':av['quantity'], 'price':int(price_instance),'error':True,'discount':discount_recived,'sp_name':specail_list.name,'sp_description':specail_list.description,'sp_start':specail_list.start,'sp_end':specail_list.end}) discount_count.append({'room':room_instance,'normal_rate':price_instance,'discount':discount_recived}) except Exception: try: price_instance = math.ceil((Decimal(price_instance) * Decimal(ex.rate))*100)/100 cost_of_rooms = math.ceil((Decimal(cost_of_rooms) * Decimal(ex.rate))*100)/100 except: pass discount_recived =Decimal(price_instance)-Decimal(cost_of_rooms) newli.append({'room': room_instance, 'display_order':room_filter.display_order, 'rm': room_filter, 'date': date_instance, 'quantity':av['quantity'], 'price': int(price_instance),'error':True}) discount_count.append({'room':room_instance,'normal_rate':price_instance,'discount':discount_recived}) template : {% for i in … -
Unable to pass data into Generic DetailView in django
I am trying to pass two models to my template view. The problem is that no data shows up in the view. Here is some code that I have tried: # views.py class ServiceDetailView(generic.DetailView): model = Service template_name = "service_detail.html" def get_context_data(self, **kwargs): context = super(ServiceDetailView, self).get_context_data(**kwargs) context['prices'] = Price.objects.filter(service__serviceid=self.kwargs.get('pk')) return context #service_detail.html <h5>Other Hospital Descriptions</h5> <ul> {% for price in prices.price_value.all %} <li>price</li> {% endfor %} Nothing is passed. Service_id is the primary key and price is linked to the service table.