Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django-table2 sort a column activate django-filter form
I try this to enable filter on tables: https://django-tables2.readthedocs.io/en/latest/pages/filtering.html but when I click on a column title to order the table, the filter form is shown. Why {% if filter %} is True when only ordering is requested? -
Django- redirect to homepage when a invalid path is typed [duplicate]
I have a web site with multiple pages and want to redirect to homepage when a user inputs an invalid path in the address bar, instead of getting the "Page not found" 404 error. How can this be achieved in Django? -
DJANGO ck-editor
In Django CK-EDITOR I am getting a whole black background type window when trying to upload the image . How Can I solve this ? Like I cant see anything here . I tried adding different kinds of skins if that works but I cant see any config options . -
Adding rows and columns to HTML table with Django
I have a problem. Consider an HTML table and it has rows and columns. I want to add a new row or column when I want it and I want it to be a record in the database. And I want to do this with django. What should I do? I think I need to use django_table2 but I don't know how. I would be glad if you write a code sample. Thank you) -
Swagger or redoc for Django Rest Framework 3.9.0
So the problem is drf-yasg supports from Django Rest Framework 3.10 and my django project is having Django Rest Framework 3.9.0. Is there is a any way to install swagger or redoc for Django Rest Framework 3.9.0? -
Can I just delete the venv folder in django to delete virtual environment?
I am trying to remove an old virtual env from a django project and just create a new one from the beginning. However, I am concerned if it is okay to just delete the venv folder through my windows file explorer. I have researched online, but I couldn't find a suitable and clear answer to this question. Thank you, and please leave a comment if you have any questions. -
How to add React JS's Link paths to DJango URLs backend
I have a project that has React as it's frontend & Django as it's backend. after i integrated React with django it works perfectly but the paths i created in React with react-router-dom doesn't load when i search the page on my browser. meaning, i can load http://127.0.0.1:8000 comfortably but if i try to search http://127.0.0.1:8000/rooms/1/UCL a path that i created with React-router-dom using it's Link, it throws an error calling Page not found how can i fix this ? #my URL.py from re import template from xml.etree.ElementInclude import include from django.contrib import admin from django.urls import path,include from django.views.generic import TemplateView urlpatterns = [ path('admin/', admin.site.urls), path('api/',include('api.urls')), path('',TemplateView.as_view(template_name='index.html')), ] my views.py import profile from rest_framework.response import Response from django.http import HttpResponse from rest_framework.decorators import api_view from app.models import * from .serializers import * from rest_framework_simplejwt.serializers import TokenObtainPairSerializer from rest_framework_simplejwt.views import TokenObtainPairView @api_view(['GET','PUT']) def updateRoomData(request,pk): try: message = Message.objects.get(id=pk) except message.DoesNotExist: return HttpResponse(status=404) if request.method=='GET': serializer = messageSerializer(message) if request.method == 'PUT': serializer = messageSerializer(message, data=request.data) if serializer.is_valid(): serializer.save() else: return Response(serializer.errors, status=400) return Response(serializer.data) -
How to get query parameter through form-data postman in django
I have this viewset which should return certian results when i give query param week, month or year. class TotalOrdersViewset(viewsets.ModelViewSet): queryset = Order.objects.all() serializer_class = OrderSerializer def list(self, request, *args, **kwargs): try: type = request.data.get('parameter') print('type= '+str(type)) if type is None: return Response({"success": False, "message": "type param describing month or week is missing."}, status=400) if type == 'month': qs = Order.objects.filter(date__month=datetime.now().month).count() return Response({'Number of orders this month': qs}) elif type == 'year': qs = Order.objects.filter(date__year=datetime.now().year).count() return Response({'Number of orders this year': qs}) elif type == 'week': TODAY = date.today() start = TODAY - timedelta(days=TODAY.weekday()) end = start + timedelta(days=6) qs = Order.objects.filter(date__range=(start, end)).count() return Response({'Number of order this week': qs}) else: return Response({}) except Exception as e: return Response({'error':str(e)}) I am specifying parameter but request.data.get is not accessing it. I have also tried request.session.get and request.POST.get. Can somebody tell me where I am wrong? Thankyou! -
Keeping track of Score in Flask
I created a website something like a quiz by collecting the questions through an API and I created a form for those questions since the name in HTML is the same it lets me select the radio button only once and I need to add the submit button to the bottom of the page can anyone help me with it? Jinja 2 {% endblock content %} {% block other %} {% for item in catt %} <div class="card quesion-card" style="width: 55rem;"> <div class="card-body"> <h6 class="card-subtitle mb-2 text-muted">{{item.question}}</h6> {% set d=item.incorrect.split(',') %} {% for ittm in d %} <form method='post' action="{{url_for('score')}}"> <input type="radio" name="ans">{{ittm.strip("[]''").title()}} {% endfor %} <input type="radio" name="answer"> {{item.correct_ans}}<br> <input class="btn btn-primary" type="submit" name="an" value="Submit" href="{{url_for('score')}}"> </div> </div> {% endfor %} {% endblock other %} </body> </html> #main code[Image of the website][1] @app.route("/Score",methods=['POST','GET']) def score(): score=0 if(request.form.get('answer')=='on'): score+=1`` return render_template('Score.html',score=score) if(__name__=="__main__"): app.run(debug=True) [1]: https://i.stack.imgur.com/U7BFY.png -
Why field change in djnago import export doesn't work?
I need to import ManyToMany relationships not by the id field, but by the number field. I know that this is done using through_fields, but I do not fully understand how to do it models.py class Part(models.Model): brand = models.CharField('Производитель', max_length=100, blank=True) number = models.CharField('Артикул', max_length=100, unique=True) name = models.CharField('Название', max_length=100, blank=True) description = models.TextField('Комментарий', blank=True, max_length=5000) analog = models.ManyToManyField('self', through='ContactConnection',blank=True, related_name='AnalogParts') images = models.FileField('Главное изображение', upload_to = 'parts/', blank=True) images0 = models.FileField('Дополнительное фото', upload_to = 'parts/', blank=True) images1 = models.FileField('Дополнительное фото', upload_to = 'parts/', blank=True) images2 = models.FileField('Дополнительное фото', upload_to = 'parts/', blank=True) def __str__(self): return str(self.number) return self.name class Meta: verbose_name = 'Запчасть' verbose_name_plural = 'Запчасти' class PartConnection(models.Model): to_part = models.ForeignKey(Part, on_delete=models.CASCADE, related_name='to_parts') from_part = models.ForeignKey(Part, on_delete=models.CASCADE, related_name='from_parts') -
Difficulty creating a serialized field
I am new to Django and overall web development. I am trying to make it so that each clothing item has a clothing type.The clothing type is a Model because users can add and remove clothing types at their discretion. But as you can seen in my test that giving it just a name of the clothing type won't work. I've been trying to figure out how to serialize the field. I have this test: def test_add_clothingitems_ok(self): token = self.get_token() res = self.client.post('/api/clothing/', data=json.dumps({ 'id':1, 'name':"fav blue shirt", 'location':"bottom drawer", 'last_worn':"2022-08-15", 'clothingType': "shirt", 'image': 'blueshirt.jpeg', }), content_type='application/json', HTTP_AUTHORIZATION=f'Bearer {token}') self.assertEquals(res.status_code, 201) result = json.loads(res.content)['data'] self.assertEquals(result['name'], 'fav blue shirt') self.assertEquals(result['location'], 'bottom drawer') self.assertEquals(result['clothingType'], 'shirt') self.assertEquals(result['last_worn'], '2022-08-15') self.assertEquals(result['image'], 'blueshirt.jpeg') That fails stating that "shirt" isn't a clothingType. My Models: class ClothingType(models.Model): """Mlodel representing a clothing type.""" name = models.CharField(max_length=30) help_text = 'Enter the clothing type (e.g. Pants, Shirts)' def __str__(self): """ String for representing the the Model object.""" return self.name class Meta: ordering = ['-id'] class ClothingItem(models.Model): """Model representing a clothing item""" name = models.CharField(max_length=50) location = models.CharField(max_length=50,blank=True) # ForeignKey used because a clothing item can only have one # clothing type, but clothing types can have multiple clothing items clothingType = … -
ForeignKey fields are not updated in one POST request
I have a model in Django which has foreign key references to other models, class Comments(models.Model): commentId = models.CharField(max_length=100, primary_key=True) chatType = models.CharField(max_length=100) commentContents = get_nullable_text_field() timeStamp = models.CharField(max_length=100) userName=models.CharField(max_length=100,default="") profilepicurl=models.CharField(max_length=100,default="") userId=models.ForeignKey(Userprofile,default=None, blank=True, null=True,on_delete=models.SET_NULL) streamId=models.ForeignKey(Streams,default=None, blank=True, null=True,on_delete=models.CASCADE) history = AuditlogHistoryField(pk_indexable=False) now when I make a POST request in django rest framework, it takes all the data fields except streamID and userID(which are foreignkeys),this statred happening after i changed streamID and userID from models.charfield to models.ForeignKey. It works when i send a second POST request with the same body. This is the serializer class class CommentsSerializer(GlanceSerializer): commentId = serializers.CharField(required=True) @transaction.atomic() def update_or_create(self, validated_data, create_only): id_field_value = {'commentId': validated_data['commentId']} data, _ = do_update_or_create(validated_data, create_only, Comments, id_field_value) return data class Meta: model = Comments fields = "__all__" -
Unable to send emails in Django
I've created an email account in the cPanel of my website and want to use it to send emails using the Django web framework. There are the configurations in my Django settings: EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_USE_TLS = True EMAIL_USE_SSL = False EMAIL_HOST = 'mail.mydomain.com' EMAIL_PORT = 2525 EMAIL_HOST_USER = os.environ.get('EMAIL_HOST_USER') EMAIL_HOST_PASSWORD = os.environ.get('EMAIL_HOST_PASSWORD') but when I run the function of ending the email I get this error: for res in _socket.getaddrinfo(host, port, family, type, proto, flags): socket.gaierror: [Errno -2] Name or service not known So, what I've missed and occurred this problem. -
Django unable to upload image using multipart/form-data
I am trying to upload a profile image for my user model on user registration, but the image is not getting saved at the media folder, and the default image is displayed. (When I edit the user's image in django admin, it gets saved). Where am I causing this problem, and how to fix it? My register function in views.py: def register(request): if request.method != 'POST': form = UserCreationForm() else: form = UserCreationForm(request.POST) if form.is_valid(): form.save() return redirect('account:login') context = {'form': form} return render(request, 'account/register.html', context) My register.html file: {% extends 'base.html' %} {% block contents %} <h1>Register</h1> <form method="post" enctype="multipart/form-data"> {% csrf_token %} {{form.as_p}} <input type="submit" name="Create User" /> </form> {% endblock %} My user creation form: class UserCreationForm(forms.ModelForm): password1 = forms.CharField(label='Password', widget=forms.PasswordInput) password2 = forms.CharField( label='Password confirmation', widget=forms.PasswordInput) class Meta: model = User fields = ('email', 'username', 'date_of_birth', 'profile_image') def clean_password2(self): password1 = self.cleaned_data.get("password1") password2 = self.cleaned_data.get("password2") if password1 and password2 and password1 != password2: raise forms.ValidationError("Passwords don't match") return password2 def save(self, commit=True): user = super().save(commit=False) user.set_password(self.cleaned_data["password1"]) if commit: user.save() return user and my User model: class UserManager(BaseUserManager): def create_user(self, email, username, date_of_birth, password, profile_image): if not email: raise ValueError('Users must have an email address') user = … -
How to read csv file with specific rows using python
I have this data that csv format and I want to read the data starting with "Date","Time","Stream 1","Stream 2","Stream 3","Stream 4","Stream 5","Stream 6","Stream 7". Data Record,,,, Radio Model,HE910-D,,, IMEI Number,32161331,,, Sim Number,9181283211,,, Signal Level,12,,, Bit Error Rate,3,,, Supply Voltage,12.1,,, Latitude,5123.2N,,, Longitude,6123.2W,,, ,,,, ,,,, ,,,, ,,,, ,,,, ,,,, ,,,, ,,,, ,,,, ,,,, ,,,, ,,,, ,,,, ,,,, "Date","Time","Stream 1","Stream 2","Stream 3","Stream 4","Stream 5","Stream 6","Stream 7" "2022-08-22","17:15:00","14","1","11","14","1","14","1" "2022-08-22","15:15:00","36","5","12","36","5","36","5" "2022-08-22","13:15:00","48","9","13","48","9","48","9" "2022-08-22","11:15:00","15","0","14","15","0","15","0" "2022-08-22","17:15:00","7","8","15","7","8","7","8" "2022-08-22","15:15:00","70","7","16","70","7","70","7" "2022-08-22","13:15:00","95","5","27","95","5","95","5" "2022-08-22","11:15:00","23","4","38","23","4","23","4" "2022-08-22","11:15:00","67","3","49","67","3","67","3" "2022-08-22","11:15:00","23","1","21","23","1","23","1" "2022-08-22","11:15:00","12","2","23","12","2","12","2" "2022-08-22","17:15:00","34","21","22","34","21","34","21" "2022-08-22","15:15:00","23","34","23","23","34","23","34" "2022-08-22","13:15:00","14","23","45","14","23","14","23" "2022-08-22","11:15:00","23","21","43","23","21","23","21" I also tried to use this code but it print all the data. Is it possible to get only the rows that start with `"Date","Time","Stream 1","Stream 2","Stream 3","Stream 4","Stream 5","Stream 6","Stream 7" with open(path + "Book1.csv", "r") as file: reader = csv.DictReader(file, delimiter=';') for l in reader: print(l) -
Why will my DNS not direct to my Heroku app?
I have a Django application I have built and deployed on Heroku. I have a custom domain I wish to use for my Heroku application. The application works perfectly on the herokuapp URL, but the custom URL doesn't seem to be working at all, what am I doing wrong? Here is the custom domain as set up on Heroku. You'll notice I blacked out the DNS target, that may not have been necessary, I just am unsure if that is something that is sensitive as I am still a bit of a noob at all this: I have added the DNS information as a CNAME on my Godaddy DNS Management: I can guarantee the DNS Target on Heroku perfectly matches the DNS Data on Godaddy. The one and only difference between the two strings is the "." that godaddy appends at the end of the data. Despite the fact that everything looks just right to me, I've waited plenty of time for the DNS servers to propagate, I still get this error when I got to http://dinpodcast.com What am I missing / doing wrong? -
Django modelform is not saving
this is my view: @login_required def createPackage(request): if request.method == "POST": print(request.POST) p_form = packageCreateForm(request.POST, instance=request.user) if p_form.is_valid(): p_form.save() x = p_form.cleaned_data.get('pickup_phoneNumber') y = p_form.cleaned_data.get('item') print(x,y) messages.success(request, f'Hi {request.user.username} you have successfully created an order with POST BOX oure customer care reperesntative will reach out to you soon ') return redirect('post-box-home') else: print("-----Form is not valid-----") else: p_form = packageCreateForm() return render(request, 'packages/createPackage.html', {'p_form': p_form}) this is the form: from django import forms from .models import Package class packageCreateForm(forms.ModelForm): class Meta: model = Package fields = ['item', 'description', 'weight', 'quantity', 'Contained_In', 'pickup_phoneNumber', 'delivery_phoneNumber', 'pickup_address','delivery_address'] i realy dont knw what am doing wrongthe form pass the valid testbut nothing is saving on the database -
Creating instance of another model within Django model manager
I have two django models defined in my models.py file - Employee model and ContactBook model as shown below: class Employee(FatCrocBaseModel): code = models.IntegerField() first_name = models.CharField(max_length=255) last_name = models.CharField(max_length=255) objects = EmployeeManager() class ContactBook(FatCrocBaseModel): employee = models.OneToOneField(Employee, on_delete=models.CASCADE) I am trying to create a custom ModelManager called EmployeeManager where the ContactBook object is automatically created for each employee (one-to-one relationship) each time a new Employee is created. The code for the ModelManager that I came up with is below: class EmployeeManager(models.Manager): def create(self, *args, **kwargs): employee = super(EmployeeManager, self).create(*args, **kwargs) ContactBook.objects.create(employee=employee) return employee I'm a new programmer in Django and would like to know if the above is an acceptable practice in Django (create ContactBook from EmployeeManager). Is there a better way to handle this? -
How to save/update a model to DB using django?
I am using django signals to update a third party service, here is what is happening: The signal is triggered whenever User is updated I would get the related model called account Update the third party service Finally, I wantto set a flag in my own DB @receiver(post_save, sender=User, dispatch_uid='get_modified_user') def update_third_party(sender, instance, **kwargs): logger.info('signal triggered') account = Account.objects.prefetch_related('related_model').get(user_id=instance.id) if not account: logger.info('account not found') else: syncer = Syncer() syncer.update_third_party(account) logger.info('save account flag') account.is_sent_to_third_party = True account.save() The above code runs fine and the third party service gets updated. I see the following output: signal triggered save account flag But when I check the DB, the value of is_sent_to_third_party flag is still false -
Django web app, scraping torrent seed,peer and complete download makes website slow
i have created a torrent site using Django but am struggling to get the peer and seed info back fast enough as i am using the tracker scrape library but its not practical to scrape every URL while rendering the page because it make the website slow, imagine there are hundred files in the site.... i have read a lot about torrent trackers and saw some open source projects here and here but i have no experience on setting them up. is there any better way get tracker info faster? scraper.py from tracker_scraper import scrape def getinfo(path): #total peers and seed total_peers = 0 total_seeds = 0 #parse file using torrent tool my_torrent = Torrent.from_file(path) #get info_hash using torrent tool info_hash = my_torrent.info_hash #Torrent urls by torrent tool announce_url = my_torrent.announce_urls url_list = [] host_list = [] port_list = [] #keep all tracker responses result = [] #parse urls using urlparse for list in announce_url: for urls in list: m = urlparse(urls) port_list.append(m.port) host_list.append(m.hostname) url_list.append(urls.rstrip("/announce")) #connect and record the response of tracker for url in url_list: try: res = scrape(tracker=url,hashes=[info_hash])[info_hash] response = { "seeds" : res['seeds'], "peers" : res['peers'], "completed" : res['complete'], "url" : url, } result.append(response) except Exception as … -
Division of a Price in Django Template Syntax
Basically, what I'm trying to do is get a 1/4 of a price in a Django Template Editor. quote.total is a generated value by the system, for example: 1235.00, and I need to manipulate that value to show 308.75 (1235.00 divided by 4). I've tried things like using {% widthratio quote.total 4 1 %} to get the quotient, however widthratio rounds the quotient, and I need an exact one. I've also tried {% widthratio quote.total 4 100 %}, to get the quotient multiplied by 100 (implying that all I'd need to do is figure out how to place a decimal point two places over), but have found no way of using CSS to place a decimal point in. It is also worth noting that because of the products I am working with quote.total will never have a value in the tenths or hundreths place. I've tried using that to my advantage by adding modulus operators and complex math rules & logic with no success. The one problem with the system I am using is I have no access to the backend to create custom functions, and because of the way the system parses the template, I cannot use script tags. -
Implementing a html templates library for app users
I’m trying to conceptualize how to build an HTML template library inside an existing django app. The app users should be able to select templates, edit the content and publish a new HTML document. This should all be done on the front end of the user's account. Similar to how MailChimp/ConvertKit has a template HTML email newsletter their users can access. So far I have looked at Wagtail and Django-CMS but wondering if anyone knows of a better way of achieving this. Thanks -
Django docker: docker-compose not running on port?
after configuring the whole file, everything looks and fires up well, but then when i navaigate the ports 0.0.0.0 nothing shows up, just dummy This site can’t be reached from google chrome, meaning everything exeutes and runs well, but why is it not showing up on the browser, i have also tried with AWS EC2 and when i run docker-compose up --build it fires up, then i copy my publick Ipv4 Address and paste it in the url input, now nothing still shows up. These are my codes for docker and docker-compose, with nginx maybe i am messing something up. Dockerfile FROM python:3.8.13-slim-buster WORKDIR /app COPY ./my_app ./ RUN pip install --upgrade pip --no-cache-dir RUN pip install -r /app/requirements.txt --no-cache-dir # CMD ["python3","manage.py","runserver","0.0.0.0:8000"] CMD ["gunicorn","investprj.wsgi:application","--bind", "0.0.0.0:8000"] docker-compose.yml version: '3' services: django_app: build: . env_file: - .env volumes: - static_vol:/app/static - media_vol:/app/media ports: - "8000:8000" nginx: build: ./nginx volumes: - static_vol:/app/static - media_vol:/app/media ports: - "80:80" depends_on: - django_app volumes: static_vol: media_vol: -
I'm getting Type error in django project while adding the products into cart
enter image description here please see my code here https://github.com/LeaderMaharshi/greatkart-django -
Django CreateView disabled field not sending field data
Django can't create item in the DB when I use CreateView with form_class. In the form_class I use disabled fields and initial data. every time I submit the form, the data never created in DB. then I tried to override post method in the class. the disabled field not send field data, altough the data already initiated view.py class CreateReport(CreateView): model = Letter form_class = LetterForm template_name_suffix="_create_form" success_url="/report/" def get_context_data(self,**kwargs): context = super().get_context_data(**kwargs) context=self.get_layout(context) return context def get_initial(self): return {"applicant": self.request.user} def get_layout(self,context): context['layout'] = Page.objects.get(layout__name="report").layout items_pra=context['layout'].items.all() q=Q() items=[] for item in items_pra: q|=Q(id=item.source_id) table=apps.get_model(app_label='component',model_name=item.type) items.append(table.objects.get(q)) context['items']=items return context form.py class LetterForm(ModelForm): def __init__(self, *args, **kwargs) -> None: super().__init__(*args, **kwargs) class Meta: model = Letter exclude=['departement_head','date_submitted','date_approved','status'] widgets = { 'applicant': Select(attrs={'disabled':True,'readonly':True}), 'about': Textarea(attrs={'rows': 3,'class':'align-items-start d-flex '}), 'research_begin': DateInput(attrs={'type':'date'}), 'research_finish': DateInput(attrs={'type':'date'}), } letter_create_form.html {% block content %} <div class="content ms-5 me-5" > <form style="margin-top:5rem" action="{% url 'create_report' %}" method="post"> {% csrf_token %} {% for field in form %} <div class="row"> <div class="col-2"> <label for="{{ field.name.id_for_label }}">{{field.name|snake2title}}: </label> </div> <div class="col-5"> {{ field}} </div> </div> {% endfor %} <input class='btn btn-outline-success mt-5 col-5' type="submit" value="Submit"> </form> </div> {% endblock content %} model.py class Letter(models.Model): applicant=models.ForeignKey('auth.User',on_delete=models.CASCADE) supervisor=models.ForeignKey('Lecturer',on_delete=models.CASCADE,related_name='letter_supervisor') departement_head=models.ForeignKey('Lecturer',on_delete=models.CASCADE,related_name='letter_departemen_head',null=True) about=models.TextField() research_begin=models.DateField() research_finish=models.DateField() date_submitted=models.DateField(auto_now=True) date_approved=models.DateField(null=True) …