Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Why my static files are not getting loaded?
i am building real estate web app. My static files are not getting loaded. I have done all the possible settings to laod my static files in my app but it doesn't work. Below is my code, could any one help me to get rid of this. {% load static %} <!DOCTYPE html> <head> <title>Marwat Real Estate</title> <link rel="stylesheet" href="{% static 'css/all.css' %}"> <!-- Bootstrap --> <link rel="stylesheet" href="{% static 'css/bootstrap.css' %}"> <!-- Custom --> <link rel="stylesheet" href="{% static 'css/style.css' %}"> <!-- light box --> <link rel="stylesheet" href="{% static 'css/lightbox.min.css' %}"> STATIC_ROOT = os.path.join(BASE_DIR, 'static') STATIC_URL = '/static/' STATICFILES_DIR = [ os.path.join(BASE_DIR, 'btre/static') ] -
How to reset database migrations in Django?
I am having issues migrating my Django app database on Heroku. I deleted previous migrations (and they are ignored by git), and whenever I run python manage.py makemigrations, I have a previous dependency showing up in the newly created (001_initial.py). Here is what I get in dependencies: dependencies = [ ('auth', '0013_auto_20190406_1745'), ] So what happens is that Django does not find those old dependencies in Heroku (it still works fine locally). I am looking for a way to reset migrations but couldn't find a solution looking into Django doc and online. I tried deleting the migrations folder and running the command python manage.py myapp zero but was unsuccessful. -
How to fix the URL not always redirecting without a trailing slash in Django
I am developing a web app in Python with Django and my url's are not consistently loading the correct view if a trailing slash is not added. The about page loads fine with and without a trailing slash yet my contact page only works if a trailing slash is added. It also affects some other pages as well. It ends up going to my single_slug function which is the last pattern in urls.py. It should do that if there is not a match in the url's but the trailing slash is obstructing the match somehow. It ends up returning HttpResponse(f"{single_slug} does not correspond to anything!"). I have attempted to add APPEND_SLASH = True in my settings.py yet it didn't change anything as it already is True by default. Here is my views.py: from django.http import HttpResponse from .models import Move, Artist from django.contrib.auth.forms import UserCreationForm, AuthenticationForm from django.contrib.auth import login, logout, authenticate from django.shortcuts import render, redirect from django.contrib import messages from .forms import NewUserForm, ContactForm # Create your views here. def homepage(request): return render(request, 'main/home.html' def about(request): return render(request, 'main/about.html') def contact(request): form_class = ContactForm return render(request, 'main/contact.html', { 'form': form_class, }) def single_slug(request, single_slug): artists = [a.artist_slug for … -
Setting model user to request.user with CreateView in Django returns "null value in column "author_id" error
I have a CreateView operating on a ModelForm, which subclasses the model Item. Item.author = ForeignKey(User,on_delete=models.CASCADE,) In the CreateView, the user fills in most of the form, but I want Item.author to be set to request.user. Whenever I do that, using form_valid() to set form.instance.author = self.request.user, I get an error back, saying "null value in column "author_id" violates not-null constraint" I've tried removing 'author' as a field to edit from the form.py. This is what I am trying to replicate: https://docs.djangoproject.com/en/2.1/topics/class-based-views/generic-editing/#models-and-request-user Model.py class Item(models.Model): # SOME OTHER FIELDS WHICH RENDER AND SAVE FINE author = models.ForeignKey(User, on_delete=models.CASCADE, def get_absolute_url(self): return reverse('item_detail',args=[str(self.id)]) ) forms.py class SubmitItemForm(forms.ModelForm): class Meta(): model = Item fields = ('link','title','excerpt','type','author') def __init__(self, *args, **kwargs): super(SubmitItemForm, self).__init__(*args, **kwargs) self.helper = FormHelper(self) self.helper.form_id = 'submit_item' self.helper.form_class = 'submit' self.helper.form_method = 'post' self.helper.form_action = 'item_detail' self.helper.add_input(Submit('submit', 'Submit')) views.py class SubmitItem(LoginRequiredMixin, generic.CreateView): login_url = '/login/' redirect_field_name = 'item_detail.html' form_class = SubmitItemForm model = Item def form_valid(self, form): form.instance.author = self.request.user return super().form_valid(form) def form_invalid(self, form): response = super().form_invalid(form) return response I'm expecting the form to save to the database, and redirect the browser to the saved data using get_absolute_url() method described on the Item model. -
web scraping using beautiful soup in django
This code is working fine. But i want to know how it is working . Can anyone help me to explain this code?? scrapper.py from bs4 import BeautifulSoup import requests def scrap(url="https://www.onlinekhabar.com/2018/12/724699"): try: res = requests.get(url) # print(res.text) # print(res.encoding) res.encoding = "utf-8" bs = BeautifulSoup(res.text, "html.parser") dict = {} dict["title"] = bs.select(".nws__title--card > h2")[0].text dict["published"] = bs.select(".post__time > span")[0].text dict["description"] = bs.select(".main__read--content")[0].text return dict except: return None if __name__ == '__main__': print(scrap()) -
Avoiding duplicate with Many-to-Many through table in Django
I am trying to build an app where users can create 'contests' (think of these as elections), fill the ballot with candidates, and then vote on them but instead of casting a single vote for one candidate, rank them in order of preference. This is my model so far: class Contest(models.Model): contest_text = models.CharField(max_length=350) pub_date = models.DateTimeField('Start Date') def __str__(self): return self.contest_text class Candidate(models.Model): contest = models.ForeignKey(Contest, on_delete=models.CASCADE, related_name='candidates') candidate_name = models.CharField(max_length=80) def __str__(self): return self.candidate_name class Ballot(models.Model): contest = models.ForeignKey(Contest, on_delete=models.CASCADE, related_name='ballots') votes = models.ManyToManyField(Candidate, through='Preference') class Preference(models.Model): candidate = models.ForeignKey(Candidate, on_delete=models.CASCADE) ballot = models.ForeignKey(Ballot, on_delete=models.CASCADE) candidate_preference = models.PositiveSmallIntegerField() However, I'd like to avoid the Preference table from having two rows for the different candidates where the preference is also the same. I.e. on the same ballot it should NOT be allowed that: John Doe, preference=1 Foo Bar, preference=1 Do I just need to control this in the HTML when someone is submitting a vote? Of course, the above should be allowed but ONLY if those two votes came from different people. I'd prefer to control this in the database as well, if possible. -
Make csv file available for download which is generated by a python script
Python script runs on click of button using ajax.The script generates a csv which i want to show to the user so that it could be downloaded.How can I achieve this? -
How to count ForeignKey set where method returns True
I'm creating a rating for contractors. A table on the page consists of the name, the amount of works he did, the rating which is calculated with (sum of ratings for works / the amount of works). I need to make queries to get the data. I have models: class CustomUser(AbstractUser): # some fields in here class Offer(models.Model): owner = ForeignKey(CustomUser) raiting = models.PositiveIntegerField() # 1-10 def func(self): # returns boolean Offer also has a func, which returns Boolean. As i said i need to count offers of each users which return True in func, a sum of raiting which return True in func and then render it all. I thought it should look like a json since we can't access some features of queries in a template, but still have no idea how to even design them -
Specifying model relationship as string vs concrete model?
Since Django provides two ways of specifying model relationship, models.ForeignKey('User') vs models.ForeignKey(User) Which one is more preferred and recommended? Is there any upside or downside of choosing one over the other? In Django documentation, all the example are of the second form but I have seen many people specifying the relationship as a string. -
Django application automatically changing ALLOWED_HOSTS during production
I have a django application running a on a google cloud compute engine instance that used the bitnami django base as my initial disk image. DEBUG is currently set to false and I set ALLOWED_HOSTS to .site.tld and the servers ip address that I got as the response to a GET request. This works perfectly for a few days at a time but after a while ALLOWED_HOSTS is automatically changed to a string representation of the current ip address and erases the other values in the array. I doesn't change any other parts of the file. Any idea what might be going on? Is django supposed to do this? Is one of the bitnami scripts doing this? Could it be the request doing this? -
How to fix social_core.exceptions.AuthMissingParameter error
I am trying to implement a google login onto my project. I already had a relatively working login scheme when I tried to use social_core's oauth with google to log in with a google account. It keeps throwing a social_core.exceptions.AuthMissingParameter error, meaning that somehow, the state isn't being passed at all. I have been following the walkthrough done here https://fosstack.com/how-to-add-google-authentication-in-django/ as a baseline for how to implement this. When I run the code from this tutorial (besides some basic syntax and version errors), everything runs like a charm. However, when I try to implement it on my project, an error I cannot resolve occurs. The url.py file I have, I have only imported some files and added the line path('auth/', include('social_django.urls', namespace='social')), Other, than that, most of my test code is similar to the blog: like this in my common file. AUTHENTICATION_BACKENDS = ( 'social_core.backends.open_id.OpenIdAuth', # for Google authentication 'social_core.backends.google.GoogleOpenId', # for Google authentication 'social_core.backends.google.GoogleOAuth2', # for Google authentication 'django.contrib.auth.backends.ModelBackend', ) How the current situation is, is that I can click login, it takes me to a login page where I type in my google account, and then it throws the following exception: Environment: Request Method: GET Request URL: http://localhost:3000/auth/complete/google-oauth2/ … -
How to pass a argument (from a Form) to a Model method and return calculation
I'm learning Python/Django and I have some trouble understanding how you call/pass argument into Models methods In my case I take a Decimal input from a Form, pass it to a my model method, and recalculate a new value based on data the Model already has in the Sqlite3 db and display this to my template If I remove the variable argument in model method and multiply by a constant directly in the model method, the code works and renders fine in the template Models: from django.db import models class Product(models.Model): name = models.CharField(max_length=30) price = models.DecimalField(max_digits=5, decimal_places=2) def __str__(self): return self.name def n_price(self, newprice): n_price = self.price * newprice return n_price Form: from django import forms class Input(forms.Form): data = forms.DecimalField(max_digits=5, decimal_places=2) Views: from django.shortcuts import render from .models import Product from .forms import Input def index(request): list = Product.objects.all() if request.method == "POST": form = Input(request.POST) else: form = Input() Product.n_price(form) #THIS IS WHERE I M LOST return render(request , 'multi/index.html', {'form' : form, 'list' : list}) Template ...``` {% block content %} <h2>New price</h2> <form method="POST" class="price-form"> {% csrf_token %} {{ form }} <button type="submit" class="save btn btn-default">Save</button> </form> {% endblock %} {% for list in list … -
How to build a django paginator with ajax?
I'm now trying to build a django paginator with ajax. I just tried a simple way, that is using $('#div_id').load() to load the article lists. But the problem of my code is the paginator didn't refresh, which means if I have a paginator like "1,2,3,...,9,10", I can only load article lists from page 1,2,3,9,10 and I cannot load lists from 4-8 because there is no page numbers in the paginator. So how can I do to fix this problem? My View.py code is: class IndexView(ListView): model = Article template_name = "articles.html" context_object_name = "article_list" paginate_by = 2 def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) paginator = context.get('paginator') page = context.get('page_obj') is_paginated = context.get('is_paginated') pagination_data = self.pagination_data(paginator, page, is_paginated) context.update(pagination_data) return context def pagination_data(self, paginator, page, is_paginated): if not is_paginated: return {} left = [] right = [] left_has_more = False right_has_more = False first = False last = False page_now = page.number page_total = paginator.num_pages page_range = paginator.page_range if page_now == 1: right = page_range[page_now:page_now + 2] if right[-1]<page_total - 1: right_has_more = True if right[-1]<page_total: last = True elif page_now == page_total: left = page_range[(page_now - 3) if (page_now - 3) > 0 else 0:page_now - 1] if left[0] > … -
How to upload JSON and file(e.g. image, doc) from Database(MySQL ) of Django app to Cloud storage and keep syncing
I have a Django app. I want to upload the JSON file generated from the MySQL database to drive/dropbox. any changes in MySQL will also update the JSON and file in stored in drive/dropbox. this JSON and file will be read by another application. I have considered about API. But what I want is to isolate the two systems. test.json { "model": "job.job", "pk": 1, "fields": { "submitted_by": 1, "job_name": "Django", "job_start": "2019-03-28T00:00:00Z", "job_end": "2019-03-28T00:00:00Z", "job_duration": "00:00:00", "image": "photos/sample.jpg", "is_published": true, "request_approval": true, } } in the test.json file for the image field, the file needs to be uploaded and updated in drive/Dropbox according to the path mentioned. -
Using XPath to fetch timestamps on a page during it is scrolling to the bottom
I'm using webdriver to fetch timestamps on a dynamic page meanwhile it's scrolling down.The issue is that I'm not able to fetch the timestamps in the exact order.for eg:- there are timestamps in the order 6 Apr(4 timestamps),5 Apr(2),4 Apr(1).But the output I get is 6 Apr , 6 Apr then it misses the other 2 and goes to 5 Apr one. Can anyone help me what I am doing wrong? What i want to achieve is that I want user to enter a date and the scrolling should end at that date.Please suggest me the best way to do this while True: try: time_stamp = browser.find_elements_by_xpath('//div[@class="_5pcp _5lel _2jyu _232_"]//span[@class="fsm fwn fcg"]/a/abbr') chk_count = len(time_stamp) dat_fin = time_stamp[chk_count-1].split(',')[0].split('/') year=int(dat_fin[2]) month=int(dat_fin[1]) day=int(dat_fin[0]) d_user = datetime(2019, 4, 3) d_fb = datetime(year, month, day) if d_fb < d_user: break #print("\n" * 10) browser.find_element_by_xpath('//div[@class="_2pid _2pin _52jv"]') print("Reached end!") break except: browser.execute_script("window.scrollTo(0, document.body.scrollHeight);") time.sleep(2) pass -
UnicodeDecodeError on django model creation on ElasticBeanstalk instance with MySQL RDS
Every time I try to create any of my own model instance through django admin, it throws me 500 Internal Server Error and in logs, it shows response = get_response(request) File "/opt/python/run/venv/local/lib/python3.6/site-packages/django/utils/deprecation.py", line 94, in __call__ response = response or self.get_response(request) .... File "/opt/python/run/venv/lib64/python3.6/encodings/ascii.py", line 26, in decode return codecs.ascii_decode(input, self.errors)[0] my "testing" model is quite simple, from django.db import models class testing(models.Model): testing_text = models.CharField(max_length=500) After registering it in admin.py, as expected, gives me a correct text form. But when I click save, it gives me the errors above. Here is a weird thing, with local sqlite, the same code works just fine locally with sqlite. But not with MySQL RDS on server. And also, all the other "default" models such as User, Group can be created on the server without issues. It just the ones I make. The same code and works as expected on local machine. But not on AWS. So I activated checked its python default encoding using venv and ran sys.getdefaultencoding() and it returns utf-8. So I am very confused what's going on here. -
How do I import variables, functions, etc. from inside a directory that's on the same level as the file I'm trying to import into?
I have something similar to the following file structure in a django project (example below is simplified). /project /directory_1 /file_1.py /file_2.py /file_3.py Inside file_1.py and file_2.py are variables, dictionaries, and functions that I want to access inside of file_3.py. file_3.py and directory_1 are on the same level. I want to import the contents of file_1.py and file_2.py that are inside directory_1, which is on the same level as file_3.py, for use inside file_3.py. -
How to fix TypeError unsupported operand type(s) for +=: 'DeferredAttribute' and 'int'
i am trying to create a fantasy-like app, i want the user's starting 11 to increase each time they add a player, and the team budget decrease by the amount of the player price. i am using the django web framework for python. here is my model for the user team class UserTeam(models.Model): name = models.CharField(max_length=50) user = models.OneToOneField(User, on_delete=models.CASCADE, default=None) players = models.ManyToManyField(Player) budget = models.IntegerField(default=100000000) FORMATION_CHOICES = ( ('4-3-3', '4-DEF 3-MID 3-ATT'), ('4-4-2', '4-DEF 4-MID 2-ATT'), ('3-4-3', '3-DEF 4-MID 3-ATT'), ('5-3-2', '5-DEF 3-MID 2-ATT'), ) formation = models.CharField(max_length=10, choices = FORMATION_CHOICES) starting_xi = models.IntegerField(default=0) bench_sub = models.IntegerField(default=0) total_score = models.IntegerField(default=0) round_score = models.IntegerField(default=0) Highest_team_score = models.IntegerField(default=0) @classmethod def transfer_player_in(cls, user, new_player): team, created = cls.objects.get_or_create( user=user ) team.players.add(new_player) @classmethod def transfer_player_out(cls, user, new_player): team, created = cls.objects.get_or_create( user=user ) team.players.remove(new_player) my player model class Player(models.Model): POSITION_CHOICES = ( ('ATT', 'Attacker'), ('MID', 'Midfielder'), ('DEF', 'Defender'), ('GK', 'GoalKeeper'), ) name = models.CharField(max_length=50) FirstName = models.CharField(max_length=20) LastName = models.CharField(max_length=20) position = models.CharField(max_length=3, choices = POSITION_CHOICES) country = models.ManyToManyField(Country) photo = models.ImageField(blank=True) price = models.IntegerField(default=0) total_score = models.IntegerField(default=0) here is the view function to handle transfer of players in and out def Transfer_Player(request, operation, pk): player= Player.objects.get(pk=pk) #gets a particular player into … -
Django + nginx - serve private files using X-Accel-Redirect
I'm new to this, but my understanding of how this works is as follows: Request private file from nginx nginx forwards this to django django does its thing, and returns a response containing the X-Accel-Redirect header nginx sees this header, and serves the file. I've set up my nginx conf like so: upstream foo_app_server { server unix:/home/project_dir/gunicorn.sock fail_timeout=0; } server { listen 80; server_name foo.com; client_max_body_size 4G; location /static/ { alias /home/projec_dir/static/; } location /media/private/ { internal; alias /home/project_dir/media/private/; } location /media/ { alias /home/project_dir/media/public/; } location / { proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_pass http://foo_app_server; } } Now, django is successfully receiving the request for files in media/private, and it is successfully attaching a X-Accel-Redirect header to the response. I've tried the following, for the content of the header, when the requested path is of the form media/private/some/path/to/file.pdf X-Accel-Redirect: media/private/some/path/to/file.pdf private/some/path/to/file.pdf path/to/file.pdf All of them gave me 404 errors. The file definitely does exist. I think this is just path issue, of a mismatch between the path in the header, and the location and the alias in the nginx conf, but I've tried for awhile and I can't get the right combination. Could somebody who has done this before suggest what … -
Django, catch and return a subpath in a url
I have a url path defined like this: path("/media/private/<path>", PrivateDocumentView.as_view()), Expecting this to catch urls of the form: /media/private/some/path/to/some/file.pdf But it doesn't. I've tried this: re_path(r"^/media/private/(?P<path>.*)$", PrivateDocumentView.as_view()), But that also doesn't work. Just a 404 error, as the url is not matching. -
Nesting python function call in Jinja logic
I am trying to use django-webp to convert .jpg images to .webp. I previously referred to my image paths using a python function call but now when I try to run webp and pass the result of my python function call, I receive errors. I have tried looking up how to use Jinja2 templates and macros as that has been a solution to similar issues however these approaches have not yet worked for me. Here is the original way in which I refer to image locations. {% for obj in object_list %} <div class = "hover-box"> <div class="grid-item" id = "hover-over"> <a href="{{ obj.get_absolute_url }}"> <button type="submit" style="background-color:transparent; border-color:transparent;"> <img class = "artwork" src="{{ obj.image.url }}"/> </button> </a> </div> <div class="filter"></div> </div> {% endfor %} The exact error I receive is: Could not parse the remainder: '{{' from '{{' Here is what I am trying to do now {% for obj in object_list %} <div class = "hover-box"> <div class="grid-item" id = "hover-over"> <a href="{{ obj.get_absolute_url }}"> <button type="submit" style="background-color:transparent; border-color:transparent;"> <img class = "artwork" src="{% webp {{ obj.image.url }} %}"/> </button> </a> </div> <div class="filter"></div> </div> {% endfor %} How should I properly pass the result of a python … -
Django, page is rendering objects after id have been deleted
I stored and object id in session, and i am getting the id to query and render values of that model, after deleting the id from the session the values of that model still show in the template after page reload, how can i stop this? here is my code def dashboard(request): customer_form = CustomerInfoForm() form = TransactionForm(initial={'tax':0,'price':0, 'price_per_item':0}) if 'id' in request.session: id = request.session['id'] print('Id in dashboard is ', id) order = Order.objects.get(pk=id).item_set.all() sum_of_price = order.aggregate(Sum('price')) #Get sum of all item prices. if sum_of_price : context['price'] = sum_of_price['price__sum'] context['current_order'] = Order.objects.get(pk=id).item_set.all() context['form'] = form context['customer_form'] = customer_form return render(request, 'main/dashboard.html', context)``` In the second view i am deleting the id and when i reload the page the first view still query and render values to the page, ```@csrf_exempt def add_order_as_credit(request): try: price = request.POST.get('price') id = request.session.get('id') order = Order.objects.get(pk=id) order.price = price order.save() print('Id is ', request.session['id']) print('Price is ' + price) del request.session['id'] return JsonResponse('Order has been set as credit', safe=False) except (KeyError, Order.DoesNotExist): return JsonResponse('There is no order ', safe=False)``` -
Creating a virtual environment results in the wrong base prefix (Django, Python installation)
I am trying to create a virtual environment following the Django tutorial (official documentation) When i type "python" at CMD, it shows me the version is 3.6 (python) However when I follow the steps to create a virutal environment: pip install virtualenvwrapper-win and then mkvirtualenv myproject It does so...but displays the following message: Using base prefix 'C:\\Python34' I obviously want it to be set up using Python 3.6. I tried editing the path environmental variable (edit text in the advanced settings), but that didn't work either. I obviously don't want it using 3.4 version as "DEPRECATION: Python 3.4 support has been deprecated. pip 19.1 will be the last one supporting it. Please upgrade your Python as Python 3.4 won't be maintained after March 2019 (cf PEP 429)." but cannot figure out how to make it install Django/PIp and everything else in the right version. Python 3.4 is located in a different place to Python 3.6 I used set PATH=%PATH%;C:\Program Files (x86)\Microsoft Visual Studio\Shared\Python36_64 to try and set it to the right path (that is where Python 3.6 is installed). Any suggestions? I have looked through the various questions but this is specific to the correct creation of a virtual env … -
RuntimeError: Model class xxx doesn't declare an explicit app_label and isn't in an application in INSTALLED_APPS
I refer to following GitHub repo which is based on Django 2.0 and cookiecutter-django: github.com/Apfelschuss/apfelschuss/tree/c8851430201daeb7d1d81c5a6b3c8a639ea27b02 I am getting the following error when trying to run the app: RuntimeError: Model class votes.models.Author doesn't declare an explicit app_label and isn't in an application in INSTALLED_APPS. Error appeared with this line of code. I tried to do as described in https://stackoverflow.com/a/40206661/5894988 but without success: config/settings/base.py LOCAL_APPS = [ "apfelschuss.votes.apps.VotesConfig" ] apfelschuss/votes/apps.py from django.apps import AppConfig class VotesConfig(AppConfig): name = "apfelschuss.votes" verbose_name = "Votes" Any idea what I am doing wrong? If anyone is interested how to run the docker container of the repo. It is described here. -
Display ploty graph on Django
How should I use ipynb file in DJango. The IPYNB file has html and python I convert that file into two seperate files. One in html and other in .py. But still not figureout how to use in django. When I convert in html file the file still show the python code when I run.