Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
My django application is deployed on heroku, can i use nginx to serve just the media and static files?
I deployed my django application on heroku. And, I want to know if i can serve the static and media files using nginx. I know i can use amazon s3 instead, but for now i dont have access to it yet cause i dont have a debit or credit card to complete my account. -
I want to know what does that code mean i see its not logic or inconsistent
I was trying to write simple django form and use authentication system, but some code doesn't look logic i can't relate it to the form and i don't know what is its impoertance {% extends "base.html" %} {% block content %} {% if form.errors %} <p>Your username and password didn't match. Please try again.</p> {% endif %} {% if next %} {% if user.is_authenticated %} <p>Your account doesn't have access to this page. To proceed, please login with an account that has access.</p> {% else %} <p>Please login to see this page.</p> {% endif %} {% endif %} <form method="post" action="{% url 'login' %}"> {% csrf_token %} <table> <tr> <td>{{ form.username.label_tag }}</td> <td>{{ form.username }}</td> </tr> <tr> <td>{{ form.password.label_tag }}</td> <td>{{ form.password }}</td> </tr> </table> <input type="submit" value="login"> <input type="hidden" name="next" value="{{ next }}"> </form> {# Assumes you setup the password_reset view in your URLconf #} <p><a href="{% url 'password_reset' %}">Lost password?</a></p> {% endblock %} why we check if user is authenticated after checking the value of next? if someone can describe the whole process to me and , what does the code in html {% if next %} mean . -
Django template permissions not working when used inside the template of an inclusion tag
I have 2 apps in a Django Project i am using to learn django. In the app A I have an inclusion tag where I am using a template named templateA.html. This inclusion tag is being used in the app B, inside the template templateB.html. The content of templateA.html is shown properly inside templateB.html. I noticed though that when I am attempting to check permissions of the user using code similar to the following: {% if perms.my_app.can_do_something %} show something here {% endif %} then, if I include that code in templateA.html it is not working, while if I use it in templateB.html it is working properly. Is there something else that needs to be done for permissions in templates when are inside templates included in other templates? Am I missing something else here? Also in case it is relevant, to mention that i am using a custom user model based on AbstractUser so i can add some more fields to the user profile. -
heroku: "Write Access Revoked" (10k limit) and Connection Refused
I'm ok with having write access refused (I have gone over the 10k rows limit), I just need to read data in my database from my web app. The site is at africanawikic.herokuapp.com. For some reason, connections to the db are refused. Can anyone help? Thanks in advance import dj_database_url DATABASES = {'default': dj_database_url.config( default='postgres://postgres:mypassword@localhost:5432/africanawiki_geodata')} -
managing database migrations in production ? Django Migrations KeyError: ('patients', 'analysesimages')?
I have a django app deployed on AWS server and it's in the testing stage now. so I'm constantly making changes in the data model however in the last push I found that 5 migration files where lost on the server they just went missing and caused many errors as there were dependencies so on the server machine I created the missing migration files manually and the server were working fine and it worked so when i worked on other changes and tried pushing the changes I got an error that i needed to merge changes and when I did the migration files went missing on my machine and when I created them manually i get these errors on both my device and the server Blockquotefor name, instance in state.models[app_label, self.model_name_lower].fields: KeyError: ('patients', 'analysesimages') so what can i do now? and is there a better way can i manage this ? -
Using existing database with fields that contains hash and usernames (and pk)
I have an existing postgres database from online game server and would like to let people log in using there unique usernames and passwords from the game. Almost new to Django and have no clues where should I start. Where to begin? Read about custom backend authentication, but not sure how to specify that table is table of users -
Why isn't this django static files working?
I want to set the config of static files in django framework. I've tried sometimes, but It can't work correctly. In setting.py DEBUG = False STATICFILES_FINDERS = [ 'django.contrib.staticfiles.finders.FileSystemFinder', 'django.contrib.staticfiles.finders.AppDirectoriesFinder', ] STATIC_URL = '/static/' STATICFILES_DIRS = ( os.path.join(BASE_DIR, 'static'), ) STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles') Some errors occurs: Uncaught SyntaxError: Unexpected token < ... I think this is static files not found error. -
hey i need a help please when i try to run the django admin server on parrot os on the terminal i get the error as
django.core.exceptions.ImproperlyConfigured: Requested setting DEBUG, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings -
Como reparar el error page no found de django [on hold]
estoy desarrollando una aplicación web, con el framework django, haciendo el modulo de restablecer la contraseña al momento de ingresar al link que envía al correo, no me encuentra la url de password_reset_confirm para realizar esto estoy utilizando las views que ofrece django para realizar esta función. , añado pantallazos de el error y del código en las urls. -
How to write it in Django?
I got the below question in Django and I am new to python, not Django. Can you please help me write this controller. This question is about analyzing view and download data to produce some meaningful insights. Here is an excerpt of two models: class Hit(models.Model): PAGEVIEW = 'PV' DOWNLOAD = 'DL' ACTIONS = ( (PAGEVIEW, 'Article web page view'), (DOWNLOAD, 'Article download'), ) publication = models.ForeignKey('Publication', on_delete=models.CASCADE) date = models.DateTimeField(default=django.utils.timezone.now) ip_address = models.GenericIPAddressField() user_agent = models.ForeignKey('UserAgent', on_delete=models.SET_NULL, null=True, blank=True) action = models.CharField(max_length=2, choices=ACTIONS) class Publication(models.Model): title = models.CharField(max_length=200) journal = models.ForeignKey('Journal', on_delete=models.CASCADE) # ... remaining fields omitted A Publication represents a single journal article on our website (example). Each time a user accesses a publication, we create a new Hit instance. A Hit represents either a single view or a single download of a publication. Publications are arranged into collections called journals - a Journal is a collection of publications of similar subject matter. Can you please write a function get_journal_statistics() that returns a dict mapping journals to summary statistics: def get_journal_statistics(): # Construct summary dict in the form {journal_id -> (total_views, total_downloads)} return summary The return value should be a dict giving summary statistics for all journals in … -
Multiple sub-fields attached to a field, and how to give the user the possibility of adding many of these fields
I am building a form in which users (composers) can add a composition. Within this form, alongside title, year, etc, they also add instrumentation. Each instrument can have a couple of properties, for example 'doubling', and the number of players. So, for instance: title: New composition instrumentation: violin doubled: no players: 1 viola doubled: yes players: 2 cello doubled: no players: 4 I have created three different models: one for instrumentation, one for the composition, and then one with a ManyToMany relation via a 'through'. models.py: class Composition(models.Model): title = models.CharField(max_length=120) # max_length = required INSTRUMENT_CHOICES = [('pno', 'piano'), ('vio1', 'violin_1(orchestral section)'), ('vio2', 'violin_2(orchestral section)'),] instrumentation = models.ManyToManyField('Instrumentation', through='DoublingAmount', related_name='compositions', max_length=10, choices=INSTRUMENT_CHOICES,) class Instrumentation(models.Model): instrumentation = models.CharField(max_length=10) class DoublingAmount(models.Model): DOUBLING_CHOICES =[(1, '1'),(2, '2'), (3, '3')] composition = models.ForeignKey(Composition, related_name='doubling_amount', on_delete=models.SET_NULL, null=True) instrumentation = models.ForeignKey(Instrumentation, related_name='doubling_amount', on_delete=models.SET_NULL, null=True) amount = models.IntegerField(choices=DOUBLING_CHOICES, default=1) forms.py: from django import forms from .models import Composition, Instrumentation class CompositionForm(forms.ModelForm): title = forms.CharField(label='Title', widget=forms.TextInput() description = forms.CharField() class Meta: model = Composition fields = [ 'title', 'instrumentation', ] views.py: def composition_create_view(request): form = CompositionForm(request.POST or None) if form.is_valid(): form.save() form = CompositionForm() context = { 'form': form } return render(request, "template.html", context) template.html: {{ form }} I … -
Django Upgrade Taking Forever
I am attempting to upgrade my Django version. I am currently on 1.10 and would like to get current with the version. I am following the recommendation in the docs to move one version at a time - so I have run pip install --upgrade django==1.11 and it currently says it is uninstalling Django 1.10. It has been doing this for nearly 2 hours now...this seems like an abnormal amount of time to me, but I've never done this before. Does it normally take this long? If not, might I have done anything wrong? It seems like a straightforward process to me. -
Django Template : Escape <script> tag only when showing RichText
I am currently developing a blog site with Django from scratch where people can write the description in a RichText Field where they can use HTML features like Bold, Italic. Heading, Add Image, Add URL etc. When rendering it from template I want to show all the tags as HTML. The only thing I want to escape is the script tag i.e. render something as something but alert("Hello world"); as <script> alert("Hello world"); </script> How can I do that? -
Serializer Method Field
I try to do hall booking app. I Have set up every things. the model and Serializer view set and urls. Now I want to return from this API 1. All halls with their booking table 2. All user Booking with hall name I try to SerializerMethodField to get all this data and it is working one side. for example, when I put SerializerMethodField in booking table ti give me the result as will as hall table. But when I try to put in both classes it give Error maximum recursion depth exceeded Model classes class HallModel(models.Model): owner = models.ForeignKey(User, on_delete=models.CASCADE, related_name='hall_owner') name = models.CharField(max_length=100) price = models.FloatField() phone = models.CharField(max_length=9, blank=True) size = models.CharField(max_length=50) region = models.CharField(max_length=100) state = models.CharField(max_length=100) image_1 = models.ImageField(upload_to='halls_image') image_2 = models.ImageField(upload_to='halls_image') image_3 = models.ImageField(upload_to='halls_image') created_at = models.DateTimeField(auto_now_add=True) class BookingModel(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, related_name='user_booking') hall = models.ForeignKey(HallModel, on_delete=models.CASCADE, related_name='hall_owner') time_date = models.DateTimeField(auto_now_add=True) booking_method = models.IntegerField() Serializer class HallSerializer(serializers.ModelSerializer): booking = serializers.SerializerMethodField() class Meta: model = HallModel fields = '__all__' def get_booking(self, obj): booking = BookingSerializer(obj.hall_owner.all(),many=True).data return booking def perform_create(self, serializer): serializer.save() class BookingSerializer(serializers.ModelSerializer): hall = serializers.SerializerMethodField() class Meta: model = BookingModel fields = '__all__' def get_hall(self, obj): serializer_data = HallSerializer(obj.hall).data return serializer_data View Sets … -
IntegrityError at /admin/first_app/post/add/
I have four models in my models.py on django app 'first_app' which UserProfile Category Post Comment When I logon to the django admin to create a post I run into this error IntegrityError at /admin/first_app/post/add/ NOT NULL constraint failed: first_app_post.status Below is the Post model class Post(models.Model): post_title = models.CharField(verbose_name='Post Title', max_length=150) category = models.ManyToManyField(Category, verbose_name='Categories of Post') author = models.ForeignKey(User, on_delete=models.CASCADE, verbose_name='Author') post_img = models.ImageField(blank=True, null=True, upload_to='uploads/post_img', verbose_name='Post Image') create_date = models.DateTimeField(default=timezone.now) published_date = models.DateTimeField(blank=True, null=True) content = models.TextField() def publish(self): self.published_date = timezone.now() self.save() def approve_comment(self): return self.comments.filter(approve_comment=True) def __str__(self): return self.title On the error above 'NOT NULL constraint failed: first_app_post.status' I remember I created status field which I later deleted I did my python manage.py makemigrations first_app python manage.py migrate I also run this command to verify that the status field is successfully deleted but I still see it in the shell when I run the following commands python manage.py dbshell .schema --indent first_app_post CREATE TABLE IF NOT EXISTS "first_app_post"( "id" integer NOT NULL PRIMARY KEY AUTOINCREMENT, "post_title" varchar(150) NOT NULL, "status" varchar(50) NOT NULL, "post_img" varchar(100) NULL, "create_date" datetime NOT NULL, "published_date" datetime NULL, "content" text NOT NULL, "author_id" integer NOT NULL REFERENCES "auth_user"("id") DEFERRABLE INITIALLY … -
How to run my Django project on Apache server on exampp server?
I'm in localhost after running Apache and MySQL ; Xampp give me a Server Erorr(500) . in apache erorr.log there is a error . it is : ModuleNotFoundError: No module named 'digionline'\r, referer: http://localhost/ my code in httpd.conf: LoadModule wsgi_module "c:/users/hameds510/appdata/local/programs/python/python37/lib/sitepackages/mod_wsgi/server/mod_wsgi.cp37-win_amd64.pyd" WSGIScriptAlias / "C:/Users/Hamed-S510/Desktop/hamed/digionline/wsgi.py" WSGIPythonHome "c:/users/hamed-s510/appdata/local/programs/python/python37" -
Vue code not updating in my Django/Vue Project
I added VueJS to my Django project using this guide. I am now trying to change the example to some code made by me, but nothing changes: assets/js/components/Demo.vue <template> <div> <p>This is just a Demo.</p> </div> </template> <script> </script> <style> </style> If i change this code, for example, to: <template> <div> <h1> test </h1> <p>TEST.</p> </div> </template> <script> </script> <style> </style> I will keep seeing the first snippet of code, in my frontend. Here is my index.js window.$ = window.jQuery = require('jquery'); require('bootstrap-sass'); import Vue from 'vue'; import Demo from "./components/Demo.vue"; window.Vue = Vue; const app = new Vue({ el: '#app', components: { Demo } }); And here is my Django template, from where Vue is called: {% load render_bundle from webpack_loader %} <html lang="en"> <head> <meta charset="UTF-8"> <title>My Django Vue</title> </head> <body> <h1>test</h1> <div id="app"> <demo></demo> </div> {% render_bundle 'main' %} </body> </html> The other parts of my Vue/JS code are basically the same of this repository, since i followed the guide https://github.com/michaelbukachi/django-vuejs-tutorial Am i missing something in my console, maybe? Should i update in some way my JS/Vue code? Any help is appreciated, thanks in advance! -
Web Scraping in Django: running scraper every day to update database or running a specific scraper for every user?
I have a project idea: a website where a user could enter search details (city, keywords, etc.) and then receive periodical job offer emails. I would like to hear your opinion on how the scraper part should work: Should I run a scraper every day? It would go through the pages of the website, building a database. Then filter the database specifically for the user and send an email with the result. Or should I build a specific scraper for every user? Every scraper would only take the information that is needed for a particular user from the website. As far as I understand django-dynamic-scraper package would fit, but it does not support the newest django version. What are your thoughts on this? Maybe there are simpler ways to implement this project? -
Unable to content Django form with extended user model
Trying to connect Django form and extended user model, but struggling to get the form to save. Basically, I'm able to authenticate user, but not save information to the CustomUser model or "profile" model for the user. I feel like I fundamentally don't understand how to extend the user model, so if you have some advice to that affect that would be very helpful. #views.py def registration(request): if request.method == "POST": form = CustomUserCreationForm(request.POST) if form.is_valid(): custom = form.save(commit=False) user = request.user custom = user.profile() custom.key = "".join(random.choice(string.digits) for i in range(20)) custom.save() username = form.cleaned_data['username'] password = form.cleaned_data['password2'] user = authenticate(request, username=username, password=password) messages.success(request, f'Your account has been created! Please proceed to agreements and payment.') return redirect('other_page') else: form = CustomUserCreationForm(request.POST) return render(request, 'registration.html', {'form': form}) Here is my models.py class CustomUser(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) key = models.CharField(max_length=25, null=True, blank=True) first_name = models.CharField(max_length=25) last_name = models.CharField(max_length=25) username = models.CharField(max_length=25) password1 = models.CharField(max_length=25) password2 = models.CharField(max_length=25) @receiver(post_save, sender=User) def create_custom_user(sender, omstamce, created, **kwargs): if created: CustomUser.objects.create(user=instance) @receiver(post_save, sender=User) def save_user_profile(sender, instance, **kwargs): if instance.CustomUser.save() def __str__(self): return f'{self.first_name} ({self.last_name})' In settings.py I added "AUTH_PROFILE_MODULE = 'app.CustomUser'". However, I'm getting this error: AttributeError: 'User' object has no attribute 'profile' -
Django datatable error - DataTables warning: table id=datatable - Ajax error
I am using datatables in Django. But when i include related data in my datatable, search function display a pop error "DataTables warning: table id=datatable - Ajax error." At the same time i also receive this error in terminal "File "C:\Dev\virenvmt\lib\site-packages\django\db\models\sql\query.py", line 1107, in build_lookup raise FieldError('Related Field got invalid lookup: {}'.format(lookup_name)) " My model is class Location(models.Model): name = models.CharField (max_length=50, null=False, blank=False, unique= True) status = models.IntegerField(blank=False, default='1') created_date = models.DateTimeField(default=datetime.now, blank=False) created_by = models.IntegerField(blank=False) updated_date = models.DateTimeField(blank=True) update_by = models.IntegerField(blank=True) def __str__(self): return self.name class Devices(models.Model): name = models.CharField (max_length=50, null=False, blank=False, unique= True) phone_number = models.CharField (max_length=20, blank=True, unique=True) location = models.ForeignKey(Location, on_delete=models.DO_NOTHING, null=False, blank=False) status = models.IntegerField(blank=False, default='1') ip_address = models.CharField(max_length=15, null=False, blank=False, unique=True) power_status = models.IntegerField(blank=True, default='0') created_date = models.DateTimeField(default=datetime.now, blank=False) created_by = models.IntegerField(blank=False) updated_date = models.DateTimeField(blank=True) update_by = models.IntegerField(blank=True) My Javascript file is $(document).ready(function() { var dt_table = $('#datatable').dataTable({ columns: [ {"dt_table": "name"}, {"dt_table": "location"}, {"dt_table": "phone_number"}, {"dt_table": "ip_address"}, {"dt_table": "power_status", "render": function (data, type, row) { return (data === '1') ? '<span class= "badge badge-success icon-flash_on r-20">&nbsp;On</span>' : '<span class="badge badge-danger icon-flash_off blink r-20">&nbsp;Off</span>';} }, { "dt_table": "id", "orderable": false, // "defaultContent": "<a class=\"btn-fab btn-fab-sm btn-primary shadow text-white\"><i class=\"icon-pencil\"></i></a>", "targets": -1, 'render': … -
DJANGO - Static files are being collected, but they don't want to work on local server
as a newbie in Django I'm struggling with the staticfiles within my project. Whenever I take some prepared bootstrap template something is not working, same when I try to add some javascript - and have no idea why. I tried to find the answer before, but in theory, everything should work - would be awesome if someone could guide me, cuz I feel completely lost now. Everything works fine until I want to use some advanced js/css animations. It looks like in the image - the main background doesn't load, the navibar is shattered as well... My settings I think look fine - Django collect all the static files, but they don't want to work on the local server. Everything is rooted in views.py/urls.py (settings.py) STATIC_URL = '/static/' STATICFILES_DIRS = [ os.path.join(BASE_DIR, "static") ] STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles') `<!DOCTYPE html> {% load static %} <html lang="en"> <head> <meta charset="utf-8"> <title>BizPage Bootstrap Template</title> <meta content="width=device-width, initial-scale=1.0" name="viewport"> <meta content="" name="keywords"> <meta content="" name="description"> <!-- Bootstrap CSS File --> <link href="{% static 'lib/bootstrap/css/bootstrap.min.css' %}" rel="stylesheet"> <!-- Libraries CSS Files --> <link href="{% static 'lib/font-awesome/css/font-awesome.min.css' %}" rel="stylesheet"> <link href="{% static 'lib/animate/animate.min.css' %}" rel="stylesheet"> <link href="{% static 'lib/ionicons/css/ionicons.min.css' %}" rel="stylesheet"> <link href="{% static 'lib/owlcarousel/assets/owl.carousel.min.css' … -
How to show assigned members its balance in html page?
I have assigned some random numbers as a balance to every user who sign up but I am not able to show them in html page. How to do it? Maybe I have made some mistakes in python files also. I have added those numbers(balance) in my database. So please let me know and correct my mistake. models.py class Payment(models.Model): payment_numbers = models.CharField(max_length=100) owner = models.ForeignKey(User, on_delete=models.CASCADE) views.py def payment(request): receiving1 = Payment.objects.filter(owner=request.user) for field in receiving1: field.payment_numbers context = { 'receiving1': receiving1 } return render(request, 'index.html', context) HTML page {% for numbers1 in receiving1 %} {% if numbers1 %} <li style="float: right;">Your Balance: Rs. {{numbers1.payment_numbers}}</li> {% endif %} {% endfor %} -
ImportError: Couldnt import Django ... Did you forget to activate a virtual environment?
I know there are several questions/answers about this but I cant figure out what I should do. So I wanted to get started with Django and installed it with pip install and added Python37 and Python37-32 to my enviromental variables and it I guess it worked because I can run several python commands in my shell. But everytime I try to python manage.py runserver it gives me an Error. I also set up my virtual environment and activated it but I think theres a problem with Django. But because I installed it with pip install django I know its there and I can use commands like django-admin startapp ... So I guess Django is working. I dont rlly know what PYTHONPATH means and where to find it. Would be pretty nice if anybody could take a look at my error. Here you can see that Django is installed : # **C:\Users\Kampet\Desktop\Python-Django\mysite>pip install django Requirement already satisfied: django in c:\users\kampet\appdata\local\programs\ python\python37-32\lib\site-packages (2.2.4) Requirement already satisfied: pytz in c:\users\kampet\appdata\local\programs\py thon\python37-32\lib\site-packages (from django) (2019.2) Requirement already satisfied: sqlparse in c:\users\kampet\appdata\local\program s\python\python37-32\lib\site-packages (from django) (0.3.0)** # And thats my error **C:\Users\Kampet\Desktop\Python-Django\mysite>python manage.py runserver Traceback (most recent call last): File "manage.py", line 10, in main … -
Why does my django pagination keeps returning the same items infinitely?
I am using django and ajax to create a infinite scroll on my website. I would like it to load more items from the database (that are in the next page) when the user scrolls to the bottom of the page. Everything is working perfectly except that it keeps returning the first page's items infinitely. For example if a user scrolls down to the end of a page instead of adding page 2's elements it just add the same elements from the first page to the bottom again. I am very sure this issue is from my views.py. I can't seem to figure out what's wrong. def feed(request): queryset2 = Store_detail.objects.filter(store_lat__gte=lat1, store_lat__lte=lat2)\ .filter(store_lng__gte=lng1, store_lng__lte=lng2) queryset3 = Paginator(queryset2, 4) page = request.GET.get('page',1) try: queryset = queryset3.page(1) except PageNotAnInteger: queryset = queryset3.page(page) except EmptyPage: queryset = "" context = { "location":location, "queryset":queryset, } # return HttpResponse(template.render(context,request)) return render(request, 'main/feed.html', {'queryset': queryset, 'location':location,}) So basically I would like to load the next page when a user scrolls to the end of the screen and if there are no more items in the next page or the next page does not exist then stop adding items. -
Converting to and from CamelCase within DRF
I am making a SOAP post request which returns data in CamelCase. I need to refactor the response back from SOAP request into snake_case. Then again I receive a request from a Restful API in snake case which I need to convert into CamelCase and then send a SOAP request. I have a mini serializer which I wrote to convert between the two, i.e. extended the to_representation method and then returned the respective CamelCase or snake_case, however I'm not sure if this mini serializer is a good way of doing it, should maybe be a helper function than serializer? Here is the serializer converting a list of objects containing name and attribute_given keys into CamelCase. class ToCamelCase(serializers.Serializer): name = serializers.CharField() attribute_given = serializers.CharField() def to_representation(self, value): data = [] for x in range(len(value)): data.append({ 'Name': value['name'], 'AttributeGiven': value['attribute_given'], }) return data I'm just looking for the best approaching solving this. Is solving this by extending the to_representation and returning custom key name at serializer level a good way or shall I write a helper function for it?