Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
deploying my django site to windows server without using IIS
I finished writing a Django application and now I want to deploy it, I have a Windows server and have successfully installed Python and Django on it, Now my app runs on localhost on my windows server, Now I want to make the site public, meaning that anyone who goes to the IP address of my windows server can browse my site, Is there a simple way to do this without using IIS? thank you -
Django trigger for more than 1 users
I am new to Django (and html) and working on a simple app that multiple user can login and choose between head or tail for the same coin for example. To simplify, let's assume there is already a database which is generated with a series of answers in advance. E.g. we have a series: "head", "head", "tail", "head", ... already generated randomly and stored somehow. (So I don't worry about the fairness right now.) And there are 3 users created as player1 ~ player3. When all players logged in, they are navigated to the matching.html page to select between head and tail. At this point, I need a single trigger for all 3 players. i.e. after all 3 players made their choice, they will be transferred to the same page for another round (or the result page). In my code, the Choice is defined as: class Choice(models.Model): pub_date = models.DateTimeField(auto_now=True) decision = models.CharField(max_length=10) author = models.ForeignKey(User, on_delete=models.CASCADE) The view is defined as: @login_required def thinkandchoose(request): choice = Choice() if(request.POST.get('choiceh')): choice.decision = 'head' print("head button pressed.") if(request.POST.get('choicet')): choice.decision = 'tail' print("tail button pressed.") choice.author = request.user choice.save() userList = get_all_logged_in_users(request) return render(request, 'versus/matching.html', context={'players': userList}) #I found this method on stackoverflow … -
Uploading Images to S3 Bucket and Storing the URL in Django DB
I have a react native application which uses Django as the backend. REST APIs are used to send and retrieve data from the DB. Everything is smooth till the point where I have text information to be uploaded to DB which is easily handled by REST API. How do I upload images to S3 from the react native application and store the URL in my DB. Do I use an Image Field or is a regular CharField enough ? Do I need to configure S3BOTO in my Django application ? -
How to link navigation bar in django?
I am new to django I want to create a responsive website im using django for it, the website works fine except for one thing when the website is switched to mobile view the navigation bar is not working. This is my urls.py from django.conf.urls import url from app import views urlpatterns =[ url(r'^$',views.index,name='index'), url(r'^about/',views.about,name='about'), url(r'^contact/',views.contact,name='contact'), url(r'^portfolio_project1/',views.portfolio_project1,name='portfolio_project1'), url(r'^portfolio_project2/',views.portfolio_project2,name='portfolio_project2'), url(r'^portfolio_project3/',views.portfolio_project1,name='portfolio_project3'), url(r'^resume/',views.resume,name='resume'), url(r'^portfolio/',views.portfolio,name='portfolio'), ] This is my header section <header role="banner" class="banner clearfix" id="banner"> <div class="section-content"> <div class="branding clearfix"> <figure id="logo"><a href="{% url "index" %}" title="Return to Home Page"><img src="{% static "images/logo.png" %}" alt="my logo" /></a></figure> <h1><a href="{% url "index" %}" title="Return to Home Page">Sriram</a></h1> <h2>Portfolio Website</h2> </div> </div> <a href="#nav" aria-controls="nav" class="nav-menu-toggle control" id="menu-toggle">Menu</a> </header> <nav role="navigation" class="nav clearfix main-nav" id="nav"> <ul class="nav-menu"> <li class="menu-item"><a href="{% url "about" %}">About</a></li> <li class="menu-item"><a href="{% url "resume" %}">Resume</a></li> <li class="menu-item"><a href="{% url "portfolio" %}">Portfolio</a> <ul class="sub-menu"> <li class="menu-item"><a href="{% url "portfolio_project1" %}">Project 1</a></li> <li class="menu-item"><a href="{% url "portfolio_project2" %}">Project 2</a></li> <li class="menu-item"><a href="{% url "portfolio_project3" %}">Project 3</a></li> </ul> </li> <li class="menu-item"><a href="{% url "contact" %}">Contact</a></li> </ul><!--/.nav-menu--> </nav> This is my views.py from django.shortcuts import render from django.http import HttpResponse def index (request): return render(request,'index.html') def about (request): return render(request,'about.html') def contact (request): return render(request,'contact.html') … -
How to get selected radio button for quiz app
So for my homework i have to do something like quiz app on Django, ive come up with models and views that are given below. And i cant find a way to get radio boxes that are checked to compare their value to right answer for each question. Even when i'll find a way to get checked radioboxes, how to check if they are "right answer" checkboxes, and to which question they belong? It's important because later i have to do randomizer for questions so they would be in random order on the page. My template code <form method="post"> {% csrf_token %} {% for question in questions %} <p class="questiontext">Question {{ forloop.counter }}/{{ questions.count }}: {{ question.question }}</p> <p class="questionmark">Points:{{ question.mark }}</p> <p class="label">Choices:</p> <p class="option"><input type="radio" name="answer-{{ question.id }}-1">{{ question.Option1 }}</p> <p class="option"><input type="radio" name="answer-{{ question.id }}-2">{{ question.Option2 }}</p> <p class="option"><input type="radio" name="answer-{{ question.id }}-3">{{ question.Option3 }}</p> <p class="option"><input type="radio" name="answer-{{ question.id }}-4">{{ question.Option4 }}</p> {% endfor %} <button type="submit">End</button> </form> My views def testpage(request, n): try: user = Student.objects.get(user=request.user) except Student.DoesNotExist: return render(request, '404.html') thistest = Test.objects.get(id=n) dt = datetime.datetime.now() questions = Question.objects.filter(test=thistest) subjects = Subject.objects.filter(groupsn=user.groupn.pk) tests = Test.objects.filter(subject__in=subjects) ctx = { 'test': thistest, 'user': user, 'questions':questions, 'dt':dt … -
I need to insert data from docx file into my sqlite db
I need to import data (text) from docx file into my sqlite db. i have this code in my models.py, but does not work. Any idea from django.db import models from django.utils import timezone from django.contrib.auth.models import User import docx2txt # Create your models here. class Post(models.Model): title = models.CharField(max_length=60) content = models.TextField() date_posted = models.DateTimeField(default=timezone.now) author = models.ForeignKey(User, on_delete=models.CASCADE) time_read = models.IntegerField(default=3) category = models.CharField(max_length=40) email = models.EmailField(User.get_email_field_name(),default='admin@linuxdude.gr') def __str__(self): return self.title def get_post(self): txt = docx2txt.process("/home/master/Downloads/test1.docx") post = Post post.title = txt.readline() post.author = "master" post.category = txt.readline() post.content = txt.readlines() post.save() -
How to autopopulate new field in models' existing objects with unique values in Django?
I have added new field in a model called slug which need to be unique. It is already existing project with models etc. During migrations Django asks what value should be used to fill already created objects. However any string will cause a conflict as value will not be unique. I was planning to fill the slug field with values from other field of this model namely username. Question: How can I populate above slug field (with unique = True) during migrations with unique values. Or maybe there is another way around that. Thanks -
Unit test for MultipleChoiceField in django tests always fails
I'm trying to do a unittest for a view with a post request with data for a form that has a MultipleChoiceField, but it always fails to success, here are my codes : the from in forms.py class AddUserForm(forms.Form): OPTIONS = ( ("إدارة عامة", "إدارة عامة"), ("إدارة المستخدمين", "إدارة المستخدمين"), ) username = forms.CharField(widget=forms.TextInput(attrs={ 'class': 'form-control', 'placeholder': 'إسم المستخدم' })) password = forms.CharField(widget=forms.PasswordInput(attrs={ 'class': 'form-control', 'placeholder': 'كلمة المرور' })) name = forms.CharField(widget=forms.TextInput(attrs={ 'class': 'form-control', 'placeholder': 'اسم الموظف ' })) branch = forms.ModelChoiceField(queryset=Branch.objects.all(), widget=forms.Select(attrs={'class': 'form-control'})) authorities = forms.MultipleChoiceField(widget=forms.CheckboxSelectMultiple, choices=OPTIONS) and the views.py @login_required def create_user(request): add_user_form = AddUserForm(request.POST) if request.method == 'POST': if add_user_form.is_valid(): username = add_user_form.cleaned_data['username'] password = add_user_form.cleaned_data['password'] name = add_user_form.cleaned_data['name'] branch = add_user_form.cleaned_data['branch'] authorities = add_user_form.cleaned_data['authorities'] check_users = User.objects.all() for item in check_users: if item.username == username: messages.error(request, 'إسم المستخدم موجود بالفعل ') else: new_user = User.objects.create_user(username=username, password=password) new_account = Account.objects.create(name=name, user=new_user, branch=branch) for unit in authorities: if unit == 'إدارة المستخدمين': section_obj = Section.objects.get(name=unit) Rule.objects.create(account=new_account, section=section_obj) return redirect('user_details', pk=new_account.id) else: add_user_form = AddUserForm(request.POST) context = { 'add_user_form': add_user_form, } return render(request, 'users/users_create.html', context) And finally here is how I tried to use `unittest: class TestCreateUser(TestCase): def setUp(self): new_user = User.objects.create_user(username='user', password='password') new_branch = Branch.objects.create(name='test branch') Account.objects.create(user=new_user, name='ay … -
Login displays same error for different types of errors
my signup form uses three fields: username password (password confirm) public PGP key but if i enter two unequal passwords and a right PGP key i still get the message "PGP is wrong formatted." instead of "Something went wrong" how can i practically solve this? def signup(request): if request.method == 'POST': form = RegistrationForm(request.POST) try: pubpgp = request.POST.get('pubpgp') # Allow redirect if pubpgp is empty or not empty but correct algorithm if not pubpgp or PGPKey.from_blob(pubpgp.rstrip("\r\n"))[0].key_algorithm == PubKeyAlgorithm.RSAEncryptOrSign: form.save() messages.success(request, 'Thanks for you Registration') return redirect(reverse('login')) else: messages.error(request, 'Something went wrong, please try again.') return render(request, 'Accounts/signup.html', {'form': form}) except Exception as e: print(e.args) messages.error(request, "PGP is wrong formated.") return render(request, 'Accounts/signup.html', {'form': form}) else: form = RegistrationForm() args = {'form': form} return render(request, 'Accounts/signup.html', args) thanks and regards :) -
Django Rest Framework - Html renderer broken?
i am currently trying to return one html page from my django rest framework setup: @action(detail=True) @renderer_classes((TemplateHTMLRenderer,)) def confirmation(self, request, *args, **kwargs): user = self.get_object() print(request.accepted_renderer) -> BrowsableAPIRenderer | WHY ? // do some business logic return Response({'user': user}, template_name='confirmation.html') But browser prints error: Object of type 'User' is not JSON serializable So my question is, why does DRF use BrowsableAPIRenderer when i specified TemplateHTMLRenderer? Can anybody help me out? TemplateHTMLRenderer is very poorly documented, so i had to ask this question.. Thanks and Greetings! -
How to improve django/python processing speed
I need to improve the processing speed of this section of code: score_forms = InstrumentScore.objects.filter(instrument=study_obj.instrument) for administration_data_item in administration_data.objects.filter(administration_id=administration_id): inst = Instrument_Forms.objects.get(instrument=study_obj.instrument,itemID=administration_data_item.item_ID) scoring_category = inst.scoring_category if inst.scoring_category else inst.item_type for f in score_forms: #items can be counted under multiple Titles check category against all categories if f.kind == "count" : if scoring_category in f.category.split(';'): if administration_data_item.value in f.measure.split(';'): #and check all values to see if we increment scoring_dict[f.title] += 1 else : if scoring_category in f.category.split(';'): scoring_dict[f.title] += administration_data_item.value + '\n' The problem is it accesses many tables and the tables aren't always linked on a ForeignKey, instead they've been linked by giving a CharField that references the record in the other model. How can I improve this processing without changing the database structure? Models class administration_data(models.Model): administration = models.ForeignKey("administration") # Associated administration item_ID = models.CharField(max_length = 101) # ID associated for each CDI item value = models.CharField(max_length=200) # Response given by participant to this particular item class Meta: unique_together = ('administration', 'item_ID') # Each administation_data object must have a unique combination of administration ID and item ID. def __unicode__(self): return '%s %s' % (self.administration, self.item_ID) class Instrument_Forms(models.Model): instrument = models.ForeignKey('researcher_UI.instrument', db_index=True) itemID = models.CharField(max_length = 101, db_index=True) # ID … -
how to create a dropping list from (1 to 9) so the user can choose how many tickets to book?
so im working on a online booking project for trains and my project works fine but only the user can book 1 ticketeach time and i want to make him being able to book more than 1 ticket,base on that choice also create the amount of forms as tickets and im new with django and i dont know where to start looking for a solution for this :( Views.py imports... # Get an instance of a logger logger = logging.getLogger(__name__) # Create your views here. def details_page(request): if request.method == 'GET': end_station_id = request.GET.get('station') elif request.method == 'POST': end_station_id = request.POST.get('to_station') # print(request.GET.get('to_station')) # Ticket.objects.filter(pk__in=[1,2,3,4,5,6,7,8,9]) trips = Trip.objects.filter(end_station_id=end_station_id) context = {'trips': trips} return render(request, 'details/details.html', context) def trips_page(request, trip_id): trip = get_object_or_404(Trip, pk=trip_id) error = None ticket = None if request.method == 'POST': first_name = request.POST.get('first_name') middle_name = request.POST.get('middle_name') last_name = request.POST.get('last_name') email = request.POST.get('email') gender = request.POST.get('gender') ticket = Ticket(trip=trip, first_name=first_name, middle_name=middle_name, last_name=last_name, email=email, gender=gender) try: ticket.full_clean() ticket.save() return redirect('tickets', ticket_id=ticket.id) except ValidationError as e: error = dict(e) print(e) context = {'trip': trip, 'error': error, 'ticket': ticket} return render(request, 'details/trips.html', context) Models.py class Ticket(models.Model): GENDER = ( ('m', 'Male'), ('f', 'Female'), ) trip = models.ForeignKey(Trip, related_name="tickets", null=True, on_delete=models.CASCADE) booking_time … -
Unity upload error, what problem is this?
First of all, i apologize to all of you my English is not good. I builded Unity program for WebGL, and i wanted to upload on my django web program. But it didn't work at all. What problem is this? I moved Build folder and TemplateData folder to my django workspace, and i fixed url to /static/Build/.. is there any problem?? How can i fix this problem. An error occurred running the Unity content on this page. See your browser Javascript console for more info. The error was: Uncaught ReferenceError: gameInstance is not defined.enter image description here -
Nginx unable to proxy django application through gunicorn
I'm trying to deploy a Django app in a Ubuntu Server 18.04 using Nginx and Gunicorn. Every tool seems to work properly, at least, from logs and status points of view. The point is that if I log into my server using SSH and try to use curl, gunicorn is able to see the request and handle it. However, if I write directly my IP, I get simply the typical Welcome to nginx home page and the request is completely invisible to gunicorn, so it seems nginx is unable to locate and pass the request to the gunicorn socket. I'm using nginx 1.14.0, Django 2.2.1, Python 3.6.7, gunicorn 19.9.0 and PostgreSQL 10.8. This is my nginx config server { listen 80; server_name localhost; location /favicon.ico { access_log off; log_not_found off; } location /static/ { alias /home/django/myproject/myproject; } location / { include proxy_params; proxy_pass http://unix:/run/gunicorn.sock; } } And these are my gunicorn.sock [Unit] Description=gunicorn socket [Socket] ListenStream=/run/gunicorn.sock [Install] WantedBy=sockets.target and gunicorn.service [Unit] Description=gunicorn daemon Requires=gunicorn.socket After=network.target [Service] User=django Group=www-data WorkingDirectory=/home/django/myproject/myproject ExecStart=/home/django/myproject/myproject/myproject/bin/gunicorn \ --access-logfile - \ --workers 3 \ --bind unix:/run/gunicorn.sock \ MyProject.wsgi:application [Install] WantedBy=multi-user.target I've been following this guide (https://www.digitalocean.com/community/tutorials/how-to-set-up-django-with-postgres-nginx-and-gunicorn-on-ubuntu-18-04), where most of all has worked as expected, but with the … -
Multiple default values specified for column "id"
I use to run my website on my laptop and its database was Sqlite, recently I wanted to transfer it to DigitalOcean and I changed its database to Postgresql, but when I migrate I encounters with some problems. My Model class Profil_Eleve(models.Model): user=models.OneToOneField(User,on_delete=models.CASCADE) statut=models.CharField(max_length=250) telephone=models.CharField(max_length=250,default="Neant") niveau=models.CharField(max_length=250) ecole=models.CharField(max_length=250,default="Neant") adresse=models.CharField(max_length=250,default="Neant") eleve_or_etudiant=models.CharField(max_length=250,default="eleve") ERROR django.db.utils.ProgrammingError: multiple default values specified for column "id" of table "eleve_profil_eleve" I don't know what to do -
Django View Testing with PyTest & Factory Boy: matching query does not exist
I am testing my views using PyTest & Factory Boy. In multiple tests, I'm getting the object does not exist. The issue is that I Pdb into the method, and the object is there. ConferenceFactory is generating a Conference object that is accessible within the test_response method. The Test: class TestQuestionView: def test_response( self, conference: ConferenceFactory, request_factory: RequestFactory): self.request = request_factory.get('/conferences/detail/question/%s' % conference.pk) self.request.user = StaffFactory() response = views.QuestionView.as_view()(self.request) self.assertEqual(response.status_code, 200) My Factory class ConferenceFactory(DjangoModelFactory): class Meta: model = models.Conference id = uuid.uuid4() name = "DjangoCon" What should happen The test should be creating a Conference with the ConferenceFactory, and a request Factory with RequestFactory. The request then is to the URL for this view. I set the user as a StaffUser with another factory. The line that errors is when I make the request and return the response: response = views.QuestionView.as_view()(self.request) -
How to fix : Class 'Article' has no 'object' member
I have written this code following just for the practice of Django framework but I am getting the following errors through pylint def aba(request): article = Article.object.all() return render(request,"aba.html") { "resource": "/c:/Users/Basri/Desktop/ruyatabiri/article/views.py", "owner": "python", "code": "no-member", "severity": 8, "message": "Class 'Article' has no 'object' member", "source": "pylint", "startLineNumber": 13, "startColumn": 15, "endLineNumber": 13, "endColumn": 15 } -
filtering the main domain name
<span>Source <a href="{{magazine_article.article.actual_source}}">{{context_data.brand_obj.brand_name}}</a></span> I want to filter out any particular name from any Url. How can i do it in Django. For example i want to filter out the name "youtube" from the link "https://www.youtube.com/". Actually i am new to django .I am adding the example code and don't have any idea what to write in place of "{{context_data.brand_obj.brand_name}}" part so that i can filter out only some specific namefrom the whole URL. Thanks in advance. I have added the respective code above. -
Django Rest Framework Method \"GET\" not allowed Error?
I'm doing a CreateApiView class and this method inside class and error is : "detail": "Method \"GET\" not allowed.", def create(self, request, pk, *args, **kwargs): auction = get_object_or_404(Auction, pk=pk) date_now = datetime.now(timezone.utc) serializer = self.get_serializer(data=request.data, context={"request": request}) serializer.is_valid(raise_exception=True) serializer.save(buyer=request.user, auction=auction) bid = get_object_or_404(Bid, pk=current_bid.pk) bid.delete() return Response(serializer.data, {"detail": "You bid is retracted"}, status=status.HTTP_200_OK) -
How to kill Django Background Tasks?
I need to check if a payment is confirmed, so I can notify the user with an email. The payment token is valid for 24h. My intention is to check every 5 minutes if the payment is confirmed using the repeat feature from Django Background Tasks Now if the payment is confirmed I want to kill the task, because it becomes not only useless, it fills the database with completed tasks, and also takes processing power from server Is there a way to remove a Django Background Task? or repeat until some event happens? Celery is not an option. -
Integrating 2checkout with Django 2.2
I try to implement 2checkout to my django app (Python 3.7 and Django 2.2). I'm using the Sandox and when I see API logs my orders are successfully passed. I also chose a URL for the Passback and selected Header Redirect in my account settings. Unfortunately, I don't succeed in getting the redirection works : I get this error after twocheckout.Charge.authorize(params) if successfully executed: The view subscriptions.views.subscription_payment didn't return an HttpResponse object. It returned None instead. When I manually add an HttpResponseRedirect like this: return HttpResponseRedirect('/payment-success') the GET request is empty because it doesn't come from 2checkout. I tried to follow this tutorial https://github.com/2Checkout/2checkout-python-tutorial and it doesn't mention any HttpResponseRedirect. Could you please help me with this issue? It's really frustrating. I'm a beginner developper so maybe I missed something. Please feel free to ask any further information that would be helpful to understand my issue. Many thanks in advance -
How to fix this unfound url in django
So i have this web appliciton which have a main model Post and a sub model Comment. when i want to approve a comment(using my super user) to a Post , i am writing and a comment form then send it into approval. when the super user click Approve! somthing is going wrong and i am redirected to 404.i can't find the problem in the code. "Not Found: /comment/9/approve/" have tried to mess around with urls.py and views.py but its dosent seems to be the problem for me. in urls.py: url(r'^post/(?P<pk>\d+)/comment/$',views.add_comment_to_post,name ='add_comment_to_post'), url(r'^post/(?P<pk>\d+)$',views.PostDetailView.as_view(),name='post_detail'), in views.py: @login_required def comment_approve(request,pk): comment = get_object_or_404(Comment,pk=pk) comment.approve() return redirect('post_detail',pk=comment.post.pk) Comment model in models.py: class Comment(models.Model): post = models.ForeignKey('Myblog.post',related_name='comments',on_delete=models.CASCADE) author = models.CharField(max_length=200) text = models.TextField() created_date = models.DateTimeField(default=timezone.now) approve_comment = models.BooleanField(default=False) def approve(self): self.approved_comment = True self.save() Comment form in forms.py: class CommentForm(forms.ModelForm): class Meta: model = Comment fields = ('author','text') widgets={ 'author':forms.TextInput(attrs={'class':'textinputclass'}), 'text':forms.Textarea(attrs={'class':'editable medium-editor-textarea'}) } i except to be redirected back to the post detail view when the comment is approved -
Django 2.2.1's runserver gives circular import error instead of showing the actual error
I recently upgraded a project from Django 2.1.7 to 2.2.1. The python version in my venv is 3.6.1 After this, when I start my project on Pycharm using manage.py runserver 0.0.0.0:8000 Django stopped telling me about SyntaxErrors in my code. Instead it started giving an unrelated and incorrect message about a possible empty urls.py and suggests this might be caused by a circular import. Exception in thread django-main-thread: Traceback resolvers.py line 581, in url_patterns iter(patterns) TypeError: 'module' object is not iterable Downgrading back to Django 2.1.7 is a workaround that works. I found this ticket https://code.djangoproject.com/ticket/30500 that might be related but it was closed without resolving. But I'd like to know how to get correct error reporting back in Django 2.2.1, using Python 3.6.1. -
Django create nested json using single model
I am using Django rest framewrok, my data is stored in database as shown in below. Here "name" column includes different organization name, and I am trying is to group data based on different organization name and create json response as shown below. Json: [ { "org1": [ { "address": "france", "phone": "3" }, { "address": "uk", "phone": "4" }, { "address": "ind", "phone": "99" } ] }, { "org2": [ { "address": "Uk", "phone": "8997" } ] } ] model, serializer and viewset are shown below class OrganizationSerializer(serializers.ModelSerializer): class Meta: model = CustomerEvents fields = ('name','address','phone',) class OrganizationSerializerViewSet(generics.ModelViewSet): queryset = Organization.objects.all() serializer_class = OrganizationSerializer class Organization(models.Model): name = models.CharField(max_length=255, blank=False) address = models.CharField(max_length=255, blank=False, null=False) phone = models.CharField(max_length=255, blank=False, null=False) class Meta: ordering = ('-pk',) db_table = 'org' Please help me how can I achieve this using DRF? Thank you -
AWS EC2 Instance - Can I add ELB to an Instance Application that already has an Elastic IP and SSL?
I have an Ubuntu 18.04 LTS EC2 Instance with a deployed Django application. The instance also has an elastic IP. The Django application already has a domain name mapped to it in nginx, and it also already has an SSL certificate mapped using certbot. My question is, if I'm planning to add a load balancer with an auto scaling group, do I need to change the IPV4 in my nginx config and DNS record to the IPv4 of the load balancer after adding it, or nothing changes with the elastic IPV4 in the domain and server?