Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
my question is about TemplateDoesNotExist at /cms_wizard/create/ INHERIT
here is the issue Here is one solution I tried: "os.path.join(SETTINGS_PATH, 'templates'),"(I substituted SETTINGS_PATH with BASE_DIR, and the setting.py terminated without any errors but still the problem isn't solved. how am I supposed to inherit the template, it has to be in a folder which I should make? also, the directory of cms_wizard/create isn't making sense as shown in the image above how do I fix it. Here is my setting.py ``` TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, 'templates')], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'sekizai.context_processors.sekizai', 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', 'cms.context_processors.cms_settings', 'django.template.context_processors.i18n', ], }, }, ] ``` -
Django ORM, Sum column values through query
I have a table with the following values: user amount date John 10 2017-07-01 John 20 2019-07-01 John 30 2020-09-01 John 40 2021-11-01 ... ... ... Dan -20 2019-02-01 Dan -30 2020-04-01 Dan -40 2021-06-01 The input of the function is a range of date, for example, as follows: date_start = '2019-01-01' date_end = '2021-11-07' Expected output: For all users, for each date in this range of date, I want to return the sum of the amounts, from the current date to all previous dates like this: user amount date John 30 (10+20) 2019-07-01 John 60 (10+20+30) 2020-09-01 John 100 (10+20+30+40) 2021-11-01 ... ... ... Dan -20 2019-02-01 Dan -50 (-20-30) 2020-04-01 Dan -90 (-20-30-40) 2021-06-01 My efforts def get_sum_amount(self, date_start=None, date_end=None): date_detail = {} # Minimum date if date_start: date_detail['date__gt'] = date_start # Maximum date if date_end: date_detail['date__lt'] = date_end detail = Financial.objects.filter(Q(**date_detail)) \ .values('user') \ .annotate(sum_amount=Coalesce(Sum(F('amount')), Value(0))) but no result. -
Django Form does not display, gives error that it is unable to match urls
With Django, I am trying to display a form to edit content on a page. However I run into the following error when trying to visit the editpage view NoReverseMatch at /editpage/CSS/ Reverse for 'editpage' with keyword arguments '{'topic': ''}' not found. 1 pattern(s) tried: ['editpage\/(?P[^/]+)\/$'] Where "CSS" here is an example pulled from the link address via str:topic in urls.py. I think the issue is with my form action in editpage.html, where I reference the editpage url and I have tried numerous combinations but am unable to get it to display. Removing the form allows the link to display with no error. Any help is much appreciated. urls.py from django.urls import path from . import views urlpatterns = [ path("editpage/<str:topic>/", views.editpage, name="editpage"), ] editpage.html {% extends "encyclopedia/layout.html" %} {% block title %} Edit Page {% endblock %} {% block body %} <h1>Edit page</h1> <form action="{% url 'editpage' topic=topic %}" method="post"> {% csrf_token %} {{ form }} <input type="submit" value="submit"> </form> {% endblock %} views.py from django.shortcuts import render from django.http import HttpResponse, HttpResponseRedirect from django.urls import reverse from django import forms from . import util class EditPageForm(forms.Form): title = forms.CharField(widget=forms.TextInput(attrs={'placeholder': 'topic', 'class': 'form-control'})) article = forms.CharField(widget=forms.Textarea(attrs={'placeholder': 'Existing article', 'class': … -
Django+Angular 2 in one port
I am new in python and django. I want that my django project work with angular 2 in one port (for example localhost:8080). I visit many page, but I don't find project django that's work with angular 2 in one port. Please help me find simple project django that's work with angular 2 in one port. -
how to use foreign key to submit a form
I have an address model like this: class PrevAddress(models.Model): id = models.AutoField(primary_key=True) user = ForeignKey(User, on_delete=models.CASCADE) address_province = models.CharField(max_length=32, null=True) address_city = models.CharField(max_length=32, null=True) address = models.CharField(max_length=128, null=True) and a mapinfo models which is connected to it using a foreign key relation: class MapInfo(models.Model): id = models.AutoField(primary_key=True) user = ForeignKey(User, on_delete=models.CASCADE) prevAddress = models.ForeignKey(PrevAddress, on_delete=models.CASCADE) location = LocationField( map_attrs={ "style": "mapbox://styles/mapbox/streets-v11", "center": (51.3890, 35.6892), }, null=True) lat = models.FloatField(blank=True, null=True) long = models.FloatField(blank=True, null=True) and these are the views I wrote for the mapinfo: class MapInfoView(CreateView): template_name = 'reg/map.html' model = MapInfo fields = ['location'] success_url = '/profile/contact/prev-addresses' def form_valid(self, form): form.instance.user = self.request.user return super().form_valid(form) the issue is that each mapinfo is related to a prevaddress object and when I want to add a new mapinfo, it needs a prevaddress object id for the connection and gives me this error: NOT NULL constraint failed: reg_mapinfo.prevAddress_id. how do I add something like this to the views ... prevaddress.id = mapinfo.id ? I can choose a prevaddress object for the mapinfo from the admin page but users obviously dont have any access to it. please help me -
How to create relationships in Django models
I am not sure how I am suppose to represent my relationships correctly. Let's say I have 2 tables User and Post. For this example I will mix and match relationships between these 2 tables. relationships 1st case A user has zero-to-many posts and a post belongs to one user. I looked at the Many-to-One relationships on Django documentation and decided I can maybe model this by doing the following... class User(models.Model): pass class Post(models.Model): user = models.ForeignKey(User) I read it as a User can have many post (zero or more). A Post belongs to one (and only one) user. 2nd case A User has one-to-many posts and a Post belongs to one user This is almost identical to the first case but the difference here is that a User has one-to-many post vs. zero-to-many. I'm not sure how to model this. How do I tell my model User to own at least 1 or more posts but not zero. I may add more of the other relationships to this question if I need further clarification but for now would really like to know how this is suppose to work. The only thing I can think of is having a … -
how to calculate due date in django based on existing date
How do i calculate the due date from this model based on the date renewed. i want the due date to be 5 years after the date Renewed. I'm pretty stuck. I need help def get_deadline(): return dateRenewed() + timedelta(days=1825) class Trademark(models.Model): trademarkName = models.CharField(max_length=100) trademarkClass = models.CharField(max_length=100) dateCreated = models.DateTimeField(default=timezone.now) acknowledgeDoc = models.FileField(upload_to='acknowledge_docs', default='default.jpg') acceptanceDoc = models.FileField(upload_to='acceptance_docs/', default='default.jpg') cert = models.FileField(upload_to='trademark_cert/', default='default.jpg') renewalDoc = models.FileField(upload_to='renewalDocs', default='default.jpg') dateRenewed = models.DateTimeField(auto_now_add=False, auto_now=False, blank=True, null=True) duedate = models.DateTimeField(default=get_deadline) uploadedBy = models.ForeignKey(User, on_delete=models.RESTRICT) ``` -
Reverse for 'tagged' with arguments '('',)' not found. 1 pattern(s) tried: ['\\^tag/\\(\\?P(?P<slug>[^/]+)\\[\\-\\\\w\\]\\+\\)/\\$$']
I keep getting this error message "Reverse for 'tagged' with arguments '('',)' not found. 1 pattern(s) tried: ['\^tag/\(\?P(?P[^/]+)\[\-\\w\]\+\)/\$$']" when trying to load my base.html, because of an anchor tag. I have looked at other's posts with the same issue, but I still don't know where I'm going wrong. Please help. views.py class TagIndexView(TagMixin, ListView): template_name = 'post/index.html' model = Post paginate_by = '10' context_object_name = 'posts' def get_queryset(self): return Post.objects.filter(tags__slug=self.kwargs.get('slug')) def tagged(request): return render(request, 'blog/tagged.html', {'title': 'Tagged'}) urls.py path(r'^tag/(?P<slug>[-\w]+)/$',TagIndexView.as_view, name='tagged') base.html The anchor tag <li class="list-group-item"><a href="{% url 'tagged' tag.slug %}">Tags</a></li> But I keep getting a NoReverseMatch. In the anchor tag I have tried "tag.slug", "tag.id", "tag.pk" and some others. Thanks in advance. -
Django can't migrate to a new db
I created a new postgreSQL database and ran "python manage.py migrate" on a Django project with no migration files. This error showed up : django.db.utils.ProgrammingError: relation "app_model_name" does not exist I tried makemigrations, showmigrations, runserver, and shell and it still gave me the same error. How do I fix this? I am also using a Macbook Air with the M1 Chip -
How to create relationships with Django
Say I have two tables: TableOne and TableTwo. In both tables I have the same column column_name. The relationships are as follows: TableOne has zero-to-many of TableTwo TableTwo belongs to one-to-many of TableOne The column_name I mentioned before is shared between (same) for both TableOne and TableTwo. So I believe I should just make this into its own table, TableThree, where TableThree will have foreign keys table_one_id and table_two_id, plus other columns that aren't important for this question. The relationship will be as follows: TableOne has zero-to-many of TableThree TableThree belongs to one-to-many of TableOne TableTwo belongs to zero-to-many of TableThree TableThree belongs to one-to-many of TableTwo I can update my question to be better explained if needed. I'm quite new to databases so I'm not sure if I'm making the right design here but if I am I would like to know how to represent this in my Django models. -
Django admin how to disable absolute url?
Firstly, I'm using 3d party app that called with pinax-announcements, and I have TemplateDoesNotExist, after checking out the root cause is the models has get_absolute_url, meanwhile that view doesn't have any templates found. def get_absolute_url(self): return reverse("pinax_announcements:announcement_detail", args=[self.pk]) As docs said https://github.com/pinax/pinax-announcements#templates: Default templates are provided by the pinax-templates app in the announcements section of that project. Meanwhile, in my case I don't really need this template, because I'm just using default Django admin to reach out the announcements. So, what I'm thinking is, probably we can just disable the View on site button or maybe can also disable/remove the get_absolute_url in admin page. But, how I can achieve this? Let say, not just focus on pinax-announcements, this probably happens in another case. -
DRF: Not showing the url in the api interface
I have a simple view @api_view(['GET', 'POST']) def hello_world(request): if request.method == 'POST': return Response({"message": "Got some data!", "data": request.data}) return Response({"message": "Hello, world!"}) and in the urls path("hello_world/",hello_world,name="hello_world") But I dont see it in the browser Which urls are shown here and which are not -
How to pass data from a vanilla JS file to a django view (POST request)? I am detecting whether or not Metamask address matches the address of user
So, in my login view, i want to check if the address returned from metamask corresponds to the wallet address of the user trying to sign in. This is the javascript code i am using to do so: async function loginWithMetaMask() { const accounts = await window.ethereum.request({ method: 'eth_requestAccounts' }) .catch((e) => { console.error(e.message); return; }) if (!accounts) { return; } window.userWalletAddress = accounts[0]; console.log(accounts[0]); let data = {address : window.userWalletAddress}; const request = new XMLHttpRequest(); request.open('POST', 'accounts/login', true); request.setRequestHeader('X-Requested-With', 'XMLHttpRequest'); request.onload = () => { const data = JSON.parse(request.responseText); console.log(data); } request.send(data); return false; } as you can see : let data = {address : window.userWalletAddress}; const request = new XMLHttpRequest(); request.open('POST', 'accounts/login', true); request.setRequestHeader('X-Requested-With', 'XMLHttpRequest'); request.onload = () => { const data = JSON.parse(request.responseText); console.log(data); } request.send(data); this code snippet from loginWithMetaMask() function is responsible for sending the JSON object when a POST request is made to the 'accounts/login' url. This is my django view: def post(self, request):#, address): username = request.POST['username'] password = request.POST['password'] user = authenticate(request, username=username, password=password) if request.is_ajax(): print('connected') data = {'address': request.POST.get('address', None)} address = data[address] print(address) else: return render(request, self.template, { 'message': "MetaMask not onnected" }) #go ahead and authenticate the user … -
Django DRF: Cant see login option
I cant see login option in this I have the below REST_FRAMEWORK = { "DEFAULT_PERMISSION_CLASSES": ( "rest_framework.permissions.IsAuthenticated", ), "DEFAULT_AUTHENTICATION_CLASSES": ( "rest_framework.authentication.TokenAuthentication", "rest_framework.authentication.SessionAuthentication", ), } -
Sorting by user upvotes and downvotes not working properly
I currently have a model as such class IpAddress(models.Model): creado = models.DateTimeField(auto_now_add=True) ip_address = models.GenericIPAddressField(unique=True) class Palabra(models.Model): nombre = models.CharField(max_length=250) definicion = models.CharField(max_length=1000, unique=True) ejemplo = models.CharField(max_length=250) creado = models.DateTimeField(auto_now_add=True) user = models.ForeignKey(CustomUser, on_delete=models.SET_NULL, null=True, blank=True) anonimo = models.BooleanField(default=True) aprobada = models.BooleanField(default=False) userUpVotes = models.ManyToManyField(IpAddress, blank=True, related_name='threadUpVotes') userDownVotes = models.ManyToManyField(IpAddress, blank=True, related_name='threadDownVotes') gramatica = models.CharField(max_length=250, null=True, blank=True) pais = models.CharField(max_length=250, null=True, blank=True) And my ranking functions is as such defeniciones = Palabra.objects.prefetch_related( 'tag_set' ).filter( nombre__iexact=palabra, aprobada=True ).annotate( total_votes=Count('userUpVotes') / NullIf((Count('userUpVotes') + Count('userDownVotes')), 0)).order_by('-total_votes') I have a situation where a word has two upvotes and no downvotes. But a word with no upvotes or downvotes, ranks higher. I'm using NullIf due to postgres. -
django-pwa and ajax calls
I have a django applications, and there are some ajax' GET and POST request. I followed https://pypi.org/project/django-pwa/ and https://www.geeksforgeeks.org/make-pwa-of-a-django-project/. When I followed the blog from geeksforgeeks, my serviceworker would show, so I just followed django-pwa documentation. Now, my problem is that for my ajax GET/POST request, they are not working. Is this a related issue? Everything else works, but that. -
Django, DRF: When there are many m2m through tables, annotate() and count() are slow
I'm using postgres and have about 300,000 rows in Video, 2,000 in Tag, and these through tables have about 1.4 million rows. It may be because of the large number of through tables, but it takes a very long time to issue a query when calculating or filtering models with reference relationships. I've spent quite a bit of time on this and still haven't found a solution. How can I improve it? If there is any other information you need, please let me know. # models.py class Tag(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) name = models.CharField(unique=True, max_length=100) is_actress = models.BooleanField(default=False, db_index=True) created_at = models.DateTimeField(default=timezone.now) class Meta: ordering = ["-is_actress"] def __str__(self): return self.name class Video(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) title = models.CharField(max_length=300) thumbnail_url = models.URLField(max_length=1000) preview_url = models.URLField(max_length=1000, blank=True, null=True) embed_url = models.URLField(max_length=1000) embed_source = models.ForeignKey(EmbedSource, on_delete=models.CASCADE) duration = models.CharField(max_length=8) tags = models.ManyToManyField(Tag, blank=True, db_index=True) views = models.PositiveIntegerField(default=0, db_index=True) is_public = models.BooleanField(default=True) published_at = models.DateTimeField(default=timezone.now, db_index=True) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) class Meta: ordering = ["-published_at"] def __str__(self): return self.title # serializers.py class TagSerializer(serializers.ModelSerializer): count = serializers.IntegerField() class Meta: model = Tag fields = ("pk", "name", "is_actress", "count") # views.py class TagListPagination(PageNumberPagination): page_size = 100 class TagListView(generics.ListAPIView): serializer_class … -
Unable to add Items to cart
I'm using django and react to build a simple checkout system, and want some help to fix this error. I'm not sure whether my function for the onclick event is accurate in the programme below. I'm finding great difficulty trying to figure out why I'm not able to add Items to the cart by clicking on the cart button using onClick event. The error I'm getting on js console on browser is page not found, and the url on the console is pointing to the actual url containing the id of the element I'm trying to add. Whenever I click on the add to cart button that 404 page not found` error appears both in js console on the browser and in the django server on the terminal. The react component const ProductDetails = (props) => { const [product, setProduct] = useState({}); useEffect(() => { const id = props.match.params.id; const fetchData = async () => { try { const res = await axios.get(`${ProductDetailURL}/product/${id}`); setProduct(res.data); console.log(res.data) } catch (err) { } }; fetchData(); }, [props.match.params.id]); const handleAddToCartURL = (id) =>{ const fetchData = async () => { try { const res = await axios.post(`${AddToCartURL}/add-to-cart/${id}`); setProduct(res.data); console.log(res.data) } catch (err) { } … -
How to save data from input fields in Django?
I want to save the date that the user will select from the datetimepicker and at the same time, it will auto calculate the age using the onchange event. Here is the code from my template. <div class="form-row"> <div class="form-group col-md-2"> <label><b>Birthday: </b></label> <input class="form-control" type="date" id='birthday' onchange="ageCount()" value="{{form.c_birthday}}"> </div> </div> and here is my function ageCount() function ageCount() { var now =new Date(); var currentY= now.getFullYear(); var currentM= now.getMonth(); var dobget =document.getElementById("birthday").value; var dob= new Date(dobget); var prevY= dob.getFullYear(); var prevM= dob.getMonth(); var ageY =currentY - prevY; var ageM =Math.abs(currentM- prevM); document.getElementById('demo').value = ageY; } Everytime I use add this code, value="{{form.c_birthday}}" it saves the date that user will select, but it displays "> and I do not know how to remove that. -
Is there an alternative to using a serializer for drf-spectacular's extend_schema request param?
I'm using drf-spectacular to generate swagger/redoc API documentation. One of the most useful features is the ability to test requests via the generated swagger html page, but I'd like to enforce the application/x-www-form-urlencoded content-type so that when the request is received by my Django endpoints, the request.data has the encoded data instead of it ending up as part of a query string. drf-spectacular always seems to default to query strings e.g. /objects/action/?key=value The only way I've figured out how to do this is to use a serializer in conjunction with the request content-type e.g. @extend_schema( request={'application/x-www-form-urlencoded': DoTheActionInputsSerializer}, responses={200: DoTheActionOutputsSerializer}, methods=["POST"] ) @action(methods=['post'], detail=False) def do_the_action(self, request, *args, **kwargs): ... This works great, but it does require a lot of small serializers that may only have one or two attributes. Is there an alternative way of achieving this inside the extend_schema decorator? I was hoping something like the following would work, but doesn't request={'application/x-www-form-urlencoded': {'schema': {'foo_id': OpenApiTypes.INT}}}, -
How to properly save instance of FileField in Django
Im hoping someone can tell me what I am doing wrong and point me in the right direction. So, I am creating an array of Model objects and then doing a bulk_create at the end to save them to the database. The one thing I am having an issue with is after I added the the FileField I cannot exactly how I need to associate data with that field. The files don't end up in the upload_to folder set nor do they end up being associated with the record itself. Id also add that I am using PyPDf2 to create the PDF files before trying to associate them to an instance of my model. So to give you an idea on what I am trying to do. I am running this code to create the PDFs initially. if pdf_file_name is not None: num_pages_current_doc = page['pageRange'][-1] input_pdf = PdfFileReader(open(pdf_file_name, 'rb')) output_pdf = PdfFileWriter() for _ in range(num_pages_current_doc): output_pdf.addPage(input_pdf.getPage(page_counter)) page_counter += 1 with open(str(uuid.uuid4())+'.pdf', 'wb') as output: output_pdf.write(output) logging.info(f'Wrote filename: { output.name }') The saved file I then want to associated with a model instance below this, the code looks something like this: document = document( location=location, Field2=Field2, etc etc ..... pdf … -
Extending the _range lookup in Django, with a custom lookup
I'd like to extend the functionality of the _range lookup, so that None values are considered infinity. Rather than only being able to do: .filter(created_at_range=[start, end]) I want to be able to do also .filter(created_at_nullablerange=[None, end]), .filter(created_at_nullablerange=[start, None]) and .filter(created_at_nullablerange=[None, None]) I understand it is possible to specify custom lookups in Django: from django.db.models import Lookup class Nullablerange(Lookup): lookup_name = 'nullablerange' def as_sql(self, qn, connection): # Actual SQL text must be returned here Datetime.register_lookup(Nullablerange) However, I'd like to do this by inheriting from the already existing _range filter, as I'd like to write as less custom SQL as possible. Is this possible? Do I have better alternatives (custom managers are inappropriate, as I want this to be available for all my models with datetime fields)? In which .py file should I register my custom lookups so that they're always included? -
Why am I receiving a ValueError in my django application?
I was following this tutorial to build a simple polling application using Django and I ran into the following error: ValueError: source code cannot contain null bytes Which appears in line 3 of the following code block: urlpatterns = [ path('admin/', admin.site.urls), path('polls/', include('polls.urls')), ] I have determined that this error exclusively occurs when utilizing the include() function. Below is the stack trace that I'm getting, but aside from that I am clueless as to where to go from here. -
trying to build new Dockerfile in django app and it keeps throwing "bash: docker: command not found" error when trying to run "docker build ."
so im doing a django/DRF tutorial on udemy and were setting up a Dockerfile for the app and im not sure whats happening here but every time i try to run build dockerfile command in the terminal it doesnt seem to recognize the "docker build ." command. i cd'd into this app's filepath and the dockerfile is there so im not seeing why this is happening. im doing it exactly like the guy in the tutorial is doing so not sure why my terminal doesn't recognize this command. (yes im sure this is a stupid question lol but im a noob so bear with me) this is the error im seeing in the terminal -
Django DRF: ModelMixin Viewset: How to create a viewset to get user details and edit user details without passing id in url
Suppose my user is logged in and he want to see the user details I want to create an api end point like /userdetails/ Based on the user who logged in it should return back the details. This is my serializer class UserDetailsSerializer(serializers.ModelSerializer): class Meta: model = User fields = [ "id", "email", "first_name", "last_name", "is_staff", "is_active", "date_joined", "last_login", "modified_date", "creation_date", ] read_only_fields = [ "email", "is_staff", "is_active", "is_superuser", "date_joined", "last_login", ] Now I want to create a viewset for read and edit I want something like this class UserDetailsViewSet( mixins.UpdateModelMixin, mixins.RetrieveModelMixin, viewsets.GenericViewSet, ): queryset = User.objects.all() serializer_class = UserDetailsSerializer and router.register(r"userdetail",UserDetailsViewSet ) But the problem with the above is I dont want urls like /userdetail/<pk> instead only /userdetail. Because the <pk> can be obtained from the request.user