Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
django.core.exceptions.ImproperlyConfigured: Error loading MySQLdb module: No module named MySQLdb. Did you install mysqlclient or MySQL-python?
I wanted to install MySQL database for a Django Project which is developed in Python 2.7 I watched a lot of StackOverflow questions and responses... and i could not find a solution, but what i found is a mix between 2 answers: I had this problem when I started the classic developing mode with python manage.py runserver, the sirver could not iniciate due to: django.core.exceptions.ImproperlyConfigured: Error loading MySQLdb module: No module named MySQLdb. Did you install mysqlclient or MySQL-python? I made a lot of module installations, I installed mysqlclient wheel and MySQL-python wheel, for that I had the wheel files on my computer, you can download in: Here, but this error could not stop, and I mixed 2 solutions, first I found a recommendation that was to run python -m pip install mysqlclient And running this i got another error on wheel, so thtat, I ran the same command but instead mysqlclient I called the wheel file for mysqlclient (compatible version for my project) so: python -m pip install mysqlclient-1.4.6-cp27-cp27m-win_amd64.whl (the .whl file is the wheel and u have to download in the link below (Here), and then copy it on your project to be able call the archive (you … -
How do I use Django's ModelForm to set data in fields added by a ManyToManyField's through table?
In models.py: ingredient_name = models.CharField(primary_key=True, max_length=50) category = models.CharField(max_length=50) stock = models.IntegerField() unit = models.CharField(max_length=10) def __str__(this): return this.ingredient_name class Recipe(models.Model): recipe_name = models.CharField(primary_key=True, max_length=50) ingredients = models.ManyToManyField(Ingredient, through='RecipeIngredient') sales_price = models.IntegerField() def __str__(this): return this.recipe_name class RecipeIngredient(models.Model): recipe_name = models.ForeignKey('Recipe', models.CASCADE) ingredient_name = models.ForeignKey('Ingredient', models.CASCADE) quantity = models.IntegerField() In forms.py: class RecipeFormCreate(ModelForm): class Meta: model = Recipe fields = ('recipe_name', 'ingredients', 'sales_price') The created form looks like this: Form generated by RecipeFormCreate, with the "Ingredients" field having a list of items that can be selected Is there a way to allow the end user of this product to set the ingredient's quantity (a field added by the RecipeIngredient model) within the RecipeFormCreate form? -
Django CSV download with checkbox forms
Before the actual download, i have some checked entries to be considered. <td><input type="checkbox" name="checked" value="{{ row.CI }}" class="checkboxAll"></td> if i try using form submit, i get these checked, but then the CSV view "return response" clears the form, so i cant submit twice if needed. <button type="submit" class="btn " value="CSV" name="csv_download" onclick="this.form.submit();"> <a class="fa-solid fa-file-csv" style="padding-left: 5px; font-size: 9px;" href="#">&nbsp csv_form</a> </button> if i try using classic CSV-file download using URL, then i do not get these checked because the form is not submitted. <button type="submit" class="btn " value="csv_download" name="csv_download"> <a class="fa-solid fa-file-csv" style="padding-left: 5px; font-size: 9px;" href="{% url 'download_csv' %}?{{request.GET.urlencode}}">&nbsp csv_download</a> </button> have anybody an idea to how i come around this? -
How to solve Django Admin Date Display Error
I have Django version: 4.1.0 Final. I'm using the default db.sqlite3 and everything works fine even the admin panel, the only issue im having now is that i have another python script that is pulling data from an external API and store them in the same sqlite db and one of the columns is date (by the way all tables creates by migrations through django it self). If i add a new record from the admin panel it self it works fine, but when the script stores the data into the db and then i open the corresponding admin page that should display the records it throws this error: ValueError at /admin/web/data/ invalid literal for int() with base 10: b'23/08/2022' Request Method: GET Request URL: http://127.0.0.1:8000/admin/web/data/ Django Version: 4.1 Exception Type: ValueError Exception Value: invalid literal for int() with base 10: b'23/08/2022' Exception Location: /usr/lib/python3.10/sqlite3/dbapi2.py, line 64, in convert_date Raised during: django.contrib.admin.options.changelist_view Python Executable: /home/ameer/.local/share/virtualenvs/projectameer-cTi4_FSs/bin/python3 Python Version: 3.10.4 Python Path: ['/home/ameer/Documents/PythonProjects/projectameer', '/usr/lib/python310.zip', '/usr/lib/python3.10', '/usr/lib/python3.10/lib-dynload', '/home/ameer/.local/share/virtualenvs/projectameer-cTi4_FSs/lib/python3.10/site-packages'] Server time: Tue, 23 Aug 2022 10:58:27 +0300 The date format that i need to use is: DD/MM/YYYY (e.g. 23/08/2022) I read an article that may solve the issue but it didn't: Date format for … -
Display error if there is error in fields
Im trying to raise error for empty fields or fields which are not validating in form so Im doing this method below but I know this is not the best way... views.py : 'errors': str(form.errors), but then in Django-template I have to use if for each field and im addin custom name for each field i dont kno why i cant use Verbose_name... Template : {% if errors %} <div class="alert alert-danger"> <p> {% if KnowledgeForm.errors.KnowledgeTitle %} عنوان دانش: {{ KnowledgeForm.errors.KnowledgeTitle }} {% endif %} {% if KnowledgeForm.errors.KnowledgeTextSummary %} Summary: {{ KnowledgeForm.errors.KnowledgeTextSummary }} {% endif %} {% if KnowledgeForm.errors.KnowledgeFromDate %} from Date: {{ KnowledgeForm.errors.KnowledgeFromDate }} {% endif %} {% if KnowledgeForm.errors.KnowledgetoDate %} To date : {{ KnowledgeForm.errors.KnowledgetoDate }} {% endif %} {% if KnowledgeForm.errors.KnowledgeProcess %} Chart: {{ KnowledgeForm.errors.KnowledgeProcess }} {% endif %} {% endif %} </p> </div> {% endif %} -
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 …