Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
I wrote a way to add comments, but it didn't run
My idea is to create a model of articles and comments. When users initiate comments, they can directly create data, but adding comments in the actual operation does not respond. #views.py def details(request, article_id): detail = LifeArticle.objects.get(id=article_id) comment = LifeComment.objects.get(article=detail) return render(request, 'lifedetail.html', locals()) def addcomment(request, article_id): article = LifeArticle.objects.get(id=article_id) if request.method == "POST": content = request.POST['content'] r = LifeComment.create(article=article, user=request.user, content=content) msg = '添加成功' return render(request, 'lifedetail.html', locals()) else: return render(request, 'lifedetail.html',) #urls.py urlpatterns = [ url(r'^life/(?P<article_id>\d+)/', views.details), url(r'^article/life/(?P<article_id>\d+)/addcoment/', views.addcomment) ] #lifedetail.html {% if detail %} <div id='article'> <form action="/article/life/{{detail.id}}/addcoment/" method="POST"> {% csrf_token %} <tr> <td>{{ detail.title }}</td> <td>{{ detail.content }}</td> <td>{{ detail.user }}</td> </tr> </div> <div id="comment"> {% if comment %} <tr> <td>{{ comment.content }}</td> <td>{{ comment.user }}</td> </tr> </div> {% else %} <p>暂无评论</p> {% endif %} <input type="text" name="content"> <input type="submit" value="提交"> </form> {% else %} <p>暂无文章</p> {% endif %} {{msg}} </div> These are my code. Now I can't find the reason. I'm also looking at Django2.2's documentation to find the problem -
Which process is better for integrating angular and django?
I want to integrate angular with django ! But i have found two different ways to do so. Which is one is the best among : https://devarea.com/building-a-web-app-with-angular-django-and-django-rest/ or https://www.techiediaries.com/django-angular-tutorial/ Thank You in Advance ! -
Can't Log into Django Admin after Creating Superuser
I created a custom user in Django. I ran python manage.py makemigrations, python manage.py migrate, python manage.py createsuperuser, python manage.py runserver successfully. Then when I tried to log in user the username and password I created, the admin page kept on throwing the error "Please enter the correct username and password for a staff account. Note that both fields may be case-sensitive." Here is my code: models.py from django.db import models from django.contrib.auth.models import AbstractBaseUser, BaseUserManager # Create your models here. class MyAccountManager(BaseUserManager): def create_user(self, email, username, first_name, last_name, password=None): if not email: raise ValueError("Users must have an email address") if not username: raise ValueError("Users must have an unique username") if not first_name: raise ValueError("Users pass in a first name") if not last_name: raise ValueError("Users pass in a last name") user = self.model( email=self.normalize_email(email), username=username, first_name=first_name, last_name=last_name ) user.set_password(password) user.save(using=self._db) return user def create_superuser(self, email, username, first_name, last_name, password=None): user = self.create_user( email, username=username, first_name=first_name, last_name=last_name ) user.is_admin = True user.is_staff = True user.is_superuser = True user.save(using=self._db) return user class Profile(AbstractBaseUser): email = models.EmailField(max_length=30, unique=True) username = models.CharField(max_length=30, unique=True) first_name = models.CharField(max_length=30) last_name = models.CharField(max_length=30) date_joined = models.DateTimeField(verbose_name='date joined', auto_now_add=True) last_login = models.DateTimeField(verbose_name='last login', auto_now=True) is_admin = models.BooleanField(default=False) is_staff = … -
Django Post Request: Method Not Allowed (Axios)
When we GET, it works just fine, but when we try to POST, we are given a Method Not Received error. No idea why. urls.py from django.urls import path from django.conf.urls import url from . import views urlpatterns = [ path('api/community/', views.makeCommunity), ] views.py @api_view(['POST']) def makeCommunity(request): if request.method == 'POST': return Response(status=status.HTTP_404_NOT_FOUND) axios code const API_URL = 'http://localhost:8000/api/'; export function testCommunityPost(){ return axios.post(`${API_URL}community/`) .then(response => { console.log(response); console.log(response.data); }) .catch(error => console.log(error)) } -
Getting 500 error on redirect from PHP page when Django DEBUG=False (NGINX)
Background: Django/Wagtail on Ubuntu 18.04 with Nginx/uWSGI I have a new website for which I've set up redirects in Wagtail. The previous pages were in php, so the redirects are all of the form /somepage.php. I've set up redirects on other new Wagtail sites before with no problem, but I've never redirected from php pages. The redirects are of the form: server { listen 80; server_name www.thesite.com thesite.com; location / { return 301 https://thesite.com$request_uri; } } This setup works fine on all of our other sites, but on this site, when the /somepage.php is placed after the domain name in the browser, it generates a 500 error (when the Django settings file has DEBUG = True). I thought I'd change DEBUG to False to see the error (because nothing was showing up in either the Nginx or the uWSGI log), and when I did, the redirect worked! I'm really stumped. Any ideas? -
Django single model multiple form
I have a single table say 'push_message' to send push messages to multiple device type i.e STB,Andriod, Feature phone. I create a single model for this. But different fields are mandatory for different device type. Is there any way I may use same model with different form(Suppose STB & Android) class PushNotification(models.Model): id = models.AutoField(primary_key=True) sched_at = models.DateTimeField(default=timezone.now) message = models.TextField(max_length=500) alert_ty = models.CharField(max_length=64, choices=Options.alert_type()) title = models.CharField(max_length=127) device_ty = models.CharField(max_length=24, choices=Options.get_devices()) Based on device type few fields are may mandatory. So I want to make form based on device chosen by user. Please provide your input how may I achieve this in Django 2.1. Thanks in Advance. -
How to use class variables in same class but in different methods in python class
I have a class class BaseDAO: def __init__(self): try: BASE_DIR = os.path.dirname(os.path.abspath(__file__)) db_path = os.path.join(BASE_DIR, "sqlDB") self.conn = sqlite3.connect(db_path) self.curr = self.conn.cursor() except Exception as dbException: print("Error during conection: ", str(dbException)) def executeQuery(slef,curr, query): return [dict((cur.description[i][0], value) \ for i, value in enumerate(row)) for row in curr.execute(query)] ////I am calling that class method using this code baseDao = BaseDAO.BaseDAO() objects = baseDao.executeQuery("select * from dbName") i am getting below error : name 'curr' is not defined in method execute query -
Django - how to dynamically display image from outside source
I have been struggling for hours and cant find any answers or solutions for how to get this to work In django views I generate a variable which is an image source from another website ('https://i.etsystatic.com/8413186/r/il/57b06e/1918667731/il_570xN.1918667731_asje.jpg') I render this variable in my view as {{ mainurl }} I cant get the below code to work <img src={{ mainurl }} alt="image" style="float:left"> If i enter the UR directly to test it works fine <imgsrc='https://i.etsystatic.com/8413186/r/il/57b06e/1918667731/il_570xN.1918667731_asje.jpg'> Am I missing something obvious here? -
Filter by field with list data
I have a file field in a model that I want to filter with a list of file names. Let's say I have a file names ["wrist_movement_eeg_no_properties.zip"] (there are more but for the sake of example). I tried the examples shown in Django 'objects.filter()' with list? but it doesn't seem to work. Example Using Q() from django.db.models import Q # this is the example from the above link my_filter_qs = Q() for creator in ["wrist_movement_eeg_no_properties.zip"]: my_filter_qs = my_filter_qs | Q(file=creator) print(my_filter_qs) a = request.user.data_storage.filter(my_filter_qs) print(a.query) # SELECT "data_store_datastoragemodel"."id", "data_store_datastoragemodel"."user_id", "data_store_datastoragemodel"."file_name", "data_store_datastoragemodel"."file", "data_store_datastoragemodel"."relative_path", "data_store_datastoragemodel"."file_added_datetime", "data_store_datastoragemodel"."file_updated_datetime", "data_store_datastoragemodel"."file_path" FROM "data_store_datastoragemodel" WHERE ("data_store_datastoragemodel"."user_id" = 3 AND "data_store_datastoragemodel"."file" = wrist_movement_eeg_no_properties.zip) print(a) # <QuerySet []> Using the __in I get the same output b = request.user.data_storage.filter(file__in=['wrist_movement_eeg_no_properties.zip']) print(b.query) # SELECT "data_store_datastoragemodel"."id", "data_store_datastoragemodel"."user_id", "data_store_datastoragemodel"."file_name", "data_store_datastoragemodel"."file", "data_store_datastoragemodel"."relative_path", "data_store_datastoragemodel"."file_added_datetime", "data_store_datastoragemodel"."file_updated_datetime", "data_store_datastoragemodel"."file_path" FROM "data_store_datastoragemodel" WHERE ("data_store_datastoragemodel"."user_id" = 3 AND "data_store_datastoragemodel"."file" IN (wrist_movement_eeg_no_properties.zip)) print(b) # <QuerySet []> But this works fine when I use __contains c = self.context['request'].user.data_storage.filter(file__contains='wrist_movement_eeg_no_properties.zip') print(c.query) # SELECT "data_store_datastoragemodel"."id", "data_store_datastoragemodel"."user_id", "data_store_datastoragemodel"."file_name", "data_store_datastoragemodel"."file", "data_store_datastoragemodel"."relative_path", "data_store_datastoragemodel"."file_added_datetime", "data_store_datastoragemodel"."file_updated_datetime", "data_store_datastoragemodel"."file_path" FROM "data_store_datastoragemodel" WHERE ("data_store_datastoragemodel"."user_id" = 3 AND "data_store_datastoragemodel"."file"::text LIKE %wrist\_movement\_eeg\_no\_properties.zip%) print(c) # <QuerySet [<DataStorageModel: DataStorageModel object (7)>]> If you look at the SQL query from the first and the third example, the only … -
IS THERE ANYONE THAT CAN HELP ME BUILD A DJANGO AND PYTHON WEBSITE FOR KITCHEN REGISTRATION SYSTEM
Does anyone know where to start or guide me do the following project? I WANT TO BUILD A DJANGO AND PYTHON WEBSITE FOR KITCHEN RESERVATION WHERE FARMERS CAN GO AND BOOK A KITCHEN AND USE IT FOR THEIR PACKING AND WASHING SERVICES, the website should have these features: 1. A calendar feature so that clients can see what dates/times are available at the various kitchens. 2. A sign up request form so clients can put in their scheduling request. 3. A way for clients to make cancellation requests. 4. A wait list feature (in case someone would like to be notified that a particular date/time frees up in the event of a cancellation). 5. A payment system to accept reservation fees that also includes the ability to issue a refund (either full or partial). 6. The ability for an Administrator to run reports on kitchen usage and to analyze data trends. Plus the Administrator needs an easy way to look up information about a reservation to answer questions from clients or to make adjustments. 7. System should be web based and mobile friendly. Thank you very much -
Django Ratelimit vs Django REST framework Throttling
I'm currently using the Django Ratelimit library on my post method while using the APIView class. I'm looking to see if I should integrate the throttling tool from Django REST framework. After reading the DRF docs where it says: "Throttles do not necessarily only refer to rate-limiting requests", I've come to the conclusion that I'm not even sure if I understand what the differences are. Therefore, I would like to know if they are almost the same, or when one should be used over the other and vice-versa. -
Avoiding code duplication in django settings files
I am following Django settings best practices by using base.py, local.py, prod.py, and staging.py. My conundrum is whether or not to be okay with code duplication. Let's take this example. I need to set a URL which is used in a large dictionary of fixed values to configure a package. local.py CONF_URL = 'hard coded local value' prod.py CONF_URL = os.environ['CONF_URL'] staging.py CONF_URL = 'some other hard coded value' I then have code like PACKAGE_CONF = { 'CONF_URL': CONF_URL, 'foo1': bar, 'foo2': bar, 'foo3': bar, 'foo4': bar, 'foo5': bar, } I can't put PACKAGE_CONF in base.py because we import base from the leaf settings files and not the other way around. I can write something to post process PACKAGE_CONF like using an env file but that seems unnecessarily complicated. I can force the user to take CONF_URL from the environment but that's not a good local dev experience. And lastly I can duplicate PACKAGE_CONF in local, staging, and prod. I'm not super pleased with any of these options. Can someone with experience in writing beautiful settings files offer a better solution? -
Cannot store dictionary or object in request session in django view
I am trying to set a session in one view and read this session in another view. Trying to store a dictionary in session. request.session['staffdict'] = staffdict When i try to get dictionary from the session in second view : staffdict = request.session.get('staffdict') I get below error : Django Version: 2.2.6 Exception Type: TypeError Exception Value: Object of type 'UUID' is not JSON serializable Exception Location: /usr/lib/python3.6/json/encoder.py in default, line 180 Python Executable: /usr/local/bin/uwsgi Python Version: 3.6.8 -
Which CDI (Class Dependency Injection) Tool Should I Use? with django
Which Dependency Injection Tool Should I Use which works well with django ? -
Load css file with Jinja2 in Django
I am using Jinja2 version 2.10 with Django. I get a not found error for my css stylesheet. I have read every question on Stackoverflow related to Jinja2 templating in Django and tried all the answers, still no success. My jinja2 config file (top level in my Django project): from django.contrib.staticfiles.storage import staticfiles_storage from django.urls import reverse from jinja2 import Environment # This enables us to use Django template tags like {% url ‘index’ %} or {% static ‘path/to/static/file.js’ %} in our Jinja2 templates. def environment(**options): env = Environment(**options) env.globals.update({ 'static': staticfiles_storage.url, 'url': reverse, }) return env My html templates load as expected and the page shows in the browser, it's just the css load that isn't working. My folder structure is: Django_project -- my_app folder -- Jinja2 | -- my_app | -- .html files | -- static -- my_app -- styles -- .css file That is, jinja2 and static are both folders on the same level inside my_app folder. My base.html file: <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <!--bootstrap responsive viewport: mobile device optimization first --> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <bootstrapp css goes here> <link rel="stylesheet" type="text/css" href="/my_app/static/styles/my_app.css"> <!-- defines an area that child templates fill --> … -
Django - What is the "Best" Way to Handle Multiple GET Requests in a Single Function-based View?
I have a dropdown form that filters search results. I also have a search (ex: search=whatever). And I have pagination that puts page=# When my dropdown changes, I use jQuery to submit the form: $('#dropdown-select').change(function(e) { $('#dropdown-form').submit(); }); This is my dropdown form: <form class="form-inline" id="dropdown-form" method="GET" action="{% url 'home' %}"> <select id="dropdown-select" class="form-control mr-2" name="filter"> <option value="all" selected>All</option> <option value="classified"{% if class_filter == 'classified' %} selected{% endif %}>Classified</option> <option value="unclassified"{% if class_filter == 'unclassified' %} selected{% endif %}>Unclassified</option> </select> </form> The problem: when the dropdown form is submitted, any prior URL parameters no-longer exist in the URL. For example: if the URL was pointed to ?page=2&search=abc and I select the dropdown "Unclassified", I want the URL parameters to persist and to also add &filter=unclassified to the URL. Like so: ?page=2&search=abc&filter=unclassified My Question: What do I need to change in the dropdown form submit to allow prior URL parameters to persist? Should I modify the Javascript / jQuery code to achieve this? Should I change something in my form's action=? Here is my view. I am passing the values through my view to my template and have been using {% if search %}&search={{ search }}{% endif %} logic in my … -
Is there a way to get flexbox to work with Django?
I've imported the latest bootstrap stylesheets and placed them in my homepage.html file, however, when trying to work with the css and actually styling it, it seems to completely ignore flexbox commands which I thought bootstrap 4 already has? Is there something I'm missing? -
Django - calling function does not redirect
I want to redirect and return view after submiting form on my homepage. Unfortunately after POST nothing is happend. My homepage: def home(request): if request.method == 'POST': url = request.POST['url'] bokeh(request,url) return render(request,'home.html') def bokeh(request,url): //my calculation logic return render(request,'bokeh.html') Of course I send other attributes like dictionaries etc, but it works fine when I hardcode my url in browser. After clicking submit on my form in my homepage nothing is happend. -
Filter nested models by grandchild, return nested structure
I have the following models, with Iteration related to Version, and Version related to Regulation. I would like to return all iterations owned by the current user, but return them in a nested structure like so: [data: [{ name: "sample regulation 1", versions: [{ name: "sample version 1" iterations:[ { name: "first Iteration", id: "uuid here" }, { name: "second Iteration" id: "uuid here" }] }, { name: "sample version 2" ... }] }, { name: "sample regulation 2" ... }] I know how to fetch all the iterations in a nested structure but not filter them by user (using nested serializers), and I know how to pre-fetch and filter all the iterations by user, but not nest them. Here is my best attempt. My attempt below doesn't work because I don't know how to filter by 'grandchild' model, only by child model. queryset = Regulation.objects.filter(iterations=request.user.organization_id) Here are my models: class Regulation(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) name = models.TextField(null=False) documents = models.ManyToManyField(Document, related_name='regulation_documents', through="DocumentRegulation") portal = models.BooleanField(default=False) class Version(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) regulation = models.ForeignKey(Regulation, related_name='versions', blank=False, null=False, on_delete=models.DO_NOTHING) name = models.CharField(max_length=20, null=False) class Iteration(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) regulation = models.ForeignKey(Regulation, blank=False, on_delete=models.DO_NOTHING) version = … -
How can I define fields for serializer to link it with the foreign key related table and another table through the related table?
Imagine a simple practicing project which is about Users that are living in a city. All cities are related with a town which has some models like this: class User(AbstractBaseUser, PermissionsMixin): """Custom user model that supports using email instead of username""" first_name = models.CharField(max_length=15) last_name = models.CharField(max_length=25) email = models.EmailField(max_length=50, unique=True, blank=False) city = models.ForeignKey(City, on_delete=models.SET_NULL, null=True) is_superuser = ...... class City(models.Model): name = models.CharField(max_length=20, unique=True) town_id = models.ForeignKey(Town, on_delete=models.CASCADE, blank=False, related_name='cities') class Meta: ordering = ('town_id', 'name', ) class Town(models.Model): name = models.CharField(max_length=20, unique=True) I want jsons for user like this: { "email": "testEmail@gmail.com", "first_name": "mmmm", "last_name": "nnnnn", "phone": "124145666443", "city": { //A direct hyperlink to view of city : // For example -> http://127.0.0.1:8000/api/city/123/ } "town":{ //A direct hyperlink to view of town : // For example -> http://127.0.0.1:8000/api/town/123/ } } These are the serializers: class UserSerializer(serializers.ModelSerializer): """Serializer for the users object""" class Meta: model = get_user_model() city = CitySerializer(read_only=True) fields = ('email', 'password', 'first_name', 'last_name', 'phone', 'city') extra_kwargs = {'password': {'write_only': True}} class TownSerializer(serializers.ModelSerializer): """ Serialize for the towns object""" # cities = CitySerializer(many=True, read_only=True) cities = serializers.HyperlinkedRelatedField( many=True, read_only=True, view_name='city:detail' ) class Meta: model = Town fields = ('name', 'cities') class CitySerializer(serializers.ModelSerializer): # Get info of … -
What is the best tool/package and framework for building a web video creator/editor using python?
I started learning python a not so long ago and got a little into Django for web development and always had this idea of building a video creating/editing web application. I was wondering what would someone recommend for going in that direction with python. Much appreciated. -
How to prevent Sentry from grouping errors/alerts on a specific type of error?
I am trying to prevent sentry from grouping my errors. Specifically I log to sentry (captureMessage()) when a task is taking too long. A daemon will check this task on a regular interval. As long as the job is still "taking too long", I want it to alert me. As of now, I have I have one sentry alert where there are 10k events. Instead, I want each of these events to be an individual Sentry alert. I cannot find anything that would work. The closest thing I can find is this link. However, this does not help because I am not "splitting" these errors in to further subcategories; I simply do not want grouping to be enabled for this one particular section of my code (where I check task X). Is this possible to do in Sentry? -
Django duplicate entry 1062
I ran python manage.py migrate accounts zero then i faced an error, I checked my models multiple times it seems everything is ok but...!? This is the error: django.db.utils.IntegrityError: (1062, "Duplicate entry '1' for key 'accounts_post_user_id_ecf3e197_uniq'") User model: class User(AbstractBaseUser): id = models.BigAutoField(primary_key=True) username = models.CharField(max_length=30, unique=True) email = models.EmailField(max_length=191, unique=True) email_verified = models.BooleanField(default=False) first_name = models.CharField(max_length=30) last_name = models.CharField(max_length=30, blank=True) is_active = models.BooleanField(default=True) is_staff = models.BooleanField(default=False) is_admin = models.BooleanField(default=False) is_verified = models.BooleanField(default=False) created_at = models.DateTimeField(auto_now_add=True) objects = UserManager() USERNAME_FIELD = 'username' EMAIL_FIELD = 'email' REQUIRED_FIELDS = ['email', 'first_name', 'last_name'] def __str__(self): return self.username def has_perm(self, perm, obj=None): return self.is_admin def has_module_perms(self, app_label): return self.is_admin Post model: class Post(models.Model): id = models.BigAutoField(primary_key=True) user = models.ForeignKey(User, on_delete=models.CASCADE) channel = models.ForeignKey(Channel, on_delete=models.CASCADE, null=True, blank=True) hashed_id = models.CharField(max_length=191) text = models.TextField(max_length=270) visits = models.IntegerField(default=0) comment_status = models.BooleanField(default=True) edited = models.BooleanField(default=False) signature = models.CharField(max_length=191) deleted_at = models.DateTimeField(null=True, blank=True) created_at = models.DateTimeField(auto_now_add=True) There was 1 user with 2 posts. -
Saving data in Django using an Ajax request
I'm trying to add a form to my page, where the submitted data is saved on my DB. Since i want to avoid the page refresh when the Submit button is hit, instead of using the standard Django form, i'm using an Ajax request to send data to my view. Here is what i wanted to do: the data is submitted, then is sent to the view -> the view saves the data on my DB using its Model. The problem with my actual code is that nothing is being saved on my DB. I think that the POST request is working, though. Here is what i tried: JS/Html <script> $(document).ready(function () { $("#test").submit(function (event) { $.ajax({ type: "POST", url: "/ajtest/", data: { csrfmiddlewaretoken: "{{ csrf_token }}", state:"inactive", 'mydata': $('#test').val() // from form }, success: function () { $('#message').html("<p> Success </p>") } }); return false; }); }); </script> <form method='post' id='test'> {% csrf_token %} <input type="text"> <input type='submit' value='Test button'/> <div id='message'>Initial text</div> </form> Here is the view: i think the problem is here, since i'm using a form that i'm not really using on my template. The problem is that i don't know how to to tell my view … -
Does the exists function have a performance cost in Django's ORM?
Lets say I am trying to query a table like so: if MyModel.objects.filter(field1='some-value', field2='some-value').exists(): obj = MyModel.objects.select_related('related_model_1', 'related_model_2').get(field1='some-value', field2='some-value') else: return Response({'detail': 'Not found'}, status=status.HTTP_404_NOT_FOUND) Am I incurring a performance cost by checking the existence and then selecting the related fields? Or is it small enough to be negligible?