Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Getting an error No module named 'learning_logs' when running application in Heroku
I am working on the Django tutorial from Python Crash Course and unable to get the Learning Log application to run from Heroku.I have tried all the possibilities but still not being able to get it to run. Below is the log data : 2023-04-23T23:52:40.244383+00:00 app[web.1]: File "", line 688, in _load_unlocked 2023-04-23T23:52:40.244383+00:00 app[web.1]: File "", line 883, in exec_module 2023-04-23T23:52:40.244384+00:00 app[web.1]: File "", line 241, in _call_with_frames_removed 2023-04-23T23:52:40.244384+00:00 app[web.1]: File "/app/learning_log/learning_log/wsgi.py", line 18, in 2023-04-23T23:52:40.244384+00:00 app[web.1]: application = get_wsgi_application() 2023-04-23T23:52:40.244384+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.10/site-packages/django/core/wsgi.py", line 12, in get_wsgi_application 2023-04-23T23:52:40.244384+00:00 app[web.1]: django.setup(set_prefix=False) 2023-04-23T23:52:40.244385+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.10/site-packages/django/init.py", line 24, in setup 2023-04-23T23:52:40.244385+00:00 app[web.1]: apps.populate(settings.INSTALLED_APPS) 2023-04-23T23:52:40.244385+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.10/site-packages/django/apps/registry.py", line 91, in populate 2023-04-23T23:52:40.244385+00:00 app[web.1]: app_config = AppConfig.create(entry) 2023-04-23T23:52:40.244385+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.10/site-packages/django/apps/config.py", line 193, in create 2023-04-23T23:52:40.244386+00:00 app[web.1]: import_module(entry) 2023-04-23T23:52:40.244386+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.10/importlib/init.py", line 126, in import_module 2023-04-23T23:52:40.244386+00:00 app[web.1]: return _bootstrap._gcd_import(name[level:], package, level) 2023-04-23T23:52:40.244386+00:00 app[web.1]: File "", line 1050, in _gcd_import 2023-04-23T23:52:40.244386+00:00 app[web.1]: File "", line 1027, in _find_and_load 2023-04-23T23:52:40.244386+00:00 app[web.1]: File "", line 1004, in _find_and_load_unlocked 2023-04-23T23:52:40.244387+00:00 app[web.1]: ModuleNotFoundError: No module named 'learning_logs' 2023-04-23T23:52:40.244482+00:00 app[web.1]: [2023-04-23 23:52:40 +0000] [7] [INFO] Worker exiting (pid: 7) 2023-04-23T23:52:40.339083+00:00 app[web.1]: [2023-04-23 23:52:40 +0000] [8] [ERROR] Exception in worker process 2023-04-23T23:52:40.339084+00:00 app[web.1]: Traceback (most recent call last): … -
Django daphne: Apps aren't loaded yet
When i try to run daphne -p 8001 messanger.asgi:application I get this error: django.core.exceptions.AppRegistryNotReady: Apps aren't loaded yet. If i run server without daphne, I get this error: Listen failure: Couldn't listen on 127.0.0.1:8000: [Errno 48] Address already in use. This is my settings .py: INSTALLED_APPS = [ "channels", "chat", "django.contrib.admin", "django.contrib.auth", "django.contrib.contenttypes", "django.contrib.sessions", "django.contrib.messages", "django.contrib.staticfiles", 'django_extensions', ] ASGI_APPLICATION = "messanger.asgi.application" CHANNEL_LAYERS = { "default": { "BACKEND": "channels_redis.core.RedisChannelLayer", "CONFIG": { "hosts": [os.environ.get("REDIS_URL", "redis_url")], }, }, } This is my asgi.py: os.environ.setdefault("DJANGO_SETTINGS_MODULE", "messanger.settings") django_asgi_app = get_asgi_application() django.setup() application = ProtocolTypeRouter({ # Django's ASGI application to handle traditional HTTP requests "http": django_asgi_app, # WebSocket chat handler "websocket": AllowedHostsOriginValidator( AuthMiddlewareStack( URLRouter(chat.routing.websocket_urlpatterns) ) ), }) This is my consumer.py: class ChatConsumer(WebsocketConsumer): def connect(self): self.room_name = self.scope["url_route"]["kwargs"]["room_name"] self.room_group_name = "chat_%s" % self.room_name # Join room group channel_layer = get_channel_layer() async_to_sync(channel_layer.group_add)( self.room_group_name, self.channel_name ) self.accept() def receive(self, text_data): text_data_json = json.loads(text_data) message = text_data_json["message"] author_id = text_data_json["a"] chat_id = text_data_json["chat"] message_create = Message(content=message, author_id=author_id, chat_id=chat_id) message_create.save() print("message:", message, "author_id:", author_id, "chat_id:", chat_id) channel_layer = get_channel_layer() async_to_sync(channel_layer.group_send)( self.room_group_name, { "type": "chat_message", "message": message, "author_id": author_id, "chat_id": chat_id } ) def chat_message(self, event): message = event["message"] author_id = event["author_id"] author_username = User.objects.get(id=author_id).username chat_id = event["chat_id"] self.send(text_data=json.dumps({ "type": "chat", … -
How do I compare the values gotten from html checkbox to id of same values in database?
I am fairly new to Django and I use the 4.2 version. This is my problem. I am building a blog website, I was trying to add multiple values(tags) for each blog post, from the HTML template checkbox input to my database, which is PostgreSQL. In that database, I already have pre-stored values of items in a Tags table. This table has a ManyToMany relationship with the main Blogpost class. But I am having problems with this particular process. I am trying to add tags for each blogpost created, from the tags already set in the Tags table. The idea is that a user selects the tags they want to include in their blogpost and in the manytomany table, the ids of the tags and the blogpost are set, when the blogpost is saved. I understand that I am to get the id of the values I am trying to add from my database where they exist and include them in the blogpost but I don't exactly know how to do this. This is what my code looks like: models.py class BlogPost(models.Model): id = models.UUIDField(default=uuid.uuid4, unique=True, primary_key='True', editable=False) post_title = models.CharField(max_length=300, blank=True, null=True, verbose_name='Title of blog post') post_image = models.ImageField(upload_to='posts/%Y/%m/%d', … -
comment remonter ce problème : Erreur d'intégrité Échec de la contrainte UNIQUE : account_user.username
j'ai crée mon view de login quand je me connecte il m'affiche cette erreur voila view coresspand -
django Warning 302 in post from UpdateView
"Hello, what I need is to add a record in one model (Historico) and update the status of a record in another model (Factura) in the same form. However, I am getting a 302 error in the console. [23/Apr/2023 18:02:40] "POST /facturas/actualizar/1 HTTP/1.1" 302 0 This is my form: class FormActualizarFactura(forms.ModelForm): comentario = forms.CharField(widget=forms.Textarea) class Meta: model = Factura fields = ('estado', 'etapa', 'email', 'comentario') This is my view: class ActualizarFactura(UpdateView): model = Factura form_class = FormActualizarFactura template_name = 'facturas/fac_actualizar.html' success_url = reverse_lazy('facturas:listaFacturas') def post(self, request, *args, **kwargs): try: if super().post(request, *args, **kwargs): historico = Historico() historico.factura = isinstance(self.object, Factura) and self.object or None historico.estado = self.object.estado historico.user = request.user historico.comentario = request.POST.get('comentario') historico.save() else: # Se produjo un error al actualizar la factura messages.error(request, f'Error al actualizar la factura: {self.object.NFactura}') except Exception as e: # Se produjo un error general messages.error(request, f'Error general: {e}') return redirect('facturas:listaFacturas') Can you help me or should I implement another method to have two separate forms (but validated in a single HTML form) and each one perform its function in a TemplateView?" Update the status of a record in one model and add it to the Historico table, all from the same form. -
How to assertRaises(ValidationError) against Django Rest Framework APIView?
eg. I have my view: class MyView(APIView): def post(...): ... raise ValidationError('blah') And to my test def test_myview(...): factory = APIRequestFactory() request = factory.post('/myview', data=...) with self.assertRaises(ValidationError): MyView.as_view()(request) I get AssertionError: ValidationError not raised I tried to call it and print the result of the call: def test_myview(...): factory = APIRequestFactory() request = factory.post('/myview', data=...) resp = MyView.as_view()(request) print(resp) it's <Response status_code=400, "text/html; charset=utf-8">, so it's kind of correct if I want to test the response code etc, but what should I do if I want to assertRaises instead? -
Cannot access my phpMyAdmin DB - neither any related configuration file
I've been using a phpMyAdmin SQL DB in the past two years, which was pretty transparent to me. I inherited it from a guy that set it up for my team, and I actually got nothing but a username, password, and a Django web project that's linked to that database. Until today, any interaction with that DB was either via Django's ORM, or via the web UI of the phpMyAdmin site. Today, suddenly, for the first time, I got the following error: And that's it. I've been googling this error, and read some stack overflow threads, but they all suggest editing some configuration files in /etc, but again, I have no clue what's that about and how or where do I access those file - all I know is my username and password to the website, and my Django project's ORM queries (I know it's sad, but that's the reality). I'm the only one in the team that uses the DB, so nobody touched nothing for sure. What can I do to fix that, or to start understanding what happened here? Thanks in advance! -
nginx throws Bad Request (400)
I get this error when I attempt to access my site at: http://exhibit.technology **The Webconfs header check tool shows the following. HTTP/1.1 400 Bad Request => Server => nginx/1.14.0 (Ubuntu) Date => Sun, 23 Apr 2023 20:24:50 GMT Content-Type => text/html Connection => close X-Content-Type-Options => nosniff Referrer-Policy => same-origin** The IP address of the above URL is 192.81.211.160. When I enter it directly it works. My site loads. http://192.81.211.160 The Webconfs header check tool shows: HTTP/1.1 200 OK => Server => nginx/1.14.0 (Ubuntu) Date => Sun, 23 Apr 2023 20:23:35 GMT Content-Type => text/html; charset=utf-8 Content-Length => 6857 Connection => close X-Frame-Options => DENY Vary => Cookie X-Content-Type-Options => nosniff Referrer-Policy => same-origin The nginx error log (the lines around the report of the HTTP 400 error) is shown below (I can provide more if needed). I do not see why the IP address access works but the name access does not. Also, I do not know how to infer the problem from the log. Any help appreciated. The DNS and hosting is on Digital Ocean. The app. is written in Django and has Debug=False and ALLOWED_HOSTS populated in settings.py nginx log: 023/04/23 20:42:39 [debug] 13352#13352: *2 http upstream … -
Can you help me with connecting database models in django?
I am making a website with Django that is fed by a database that is refreshed every 3 hours, the problem is that when I want to remove a client from the database, mysql workbench does not let me because the client model is related to notes and user. How can I do so that when a client is deleted, its related classes are automatically deleted? I tried adding " on_delete=models.CASCADE" but it didn't work, also removing the foreign keys but I need to create notes from the clients. can you help me please? :c from django.db import models # Create your models here.from django.db import models from django.contrib.auth.models import User from django.utils import timezone SATISFACCION_CHOICES = ( ('<i class="fas fa-smile fa-2x" style="color:green"></i>', 'Satisfecho'), ('<i class="fas fa-meh fa-2x" style="color:rgb(255, 187, 0)"></i>', 'Intermedio/no atendió'), ('<i class="fas fa-frown fa-2x" style="color:red"></i>', 'Insatisfecho'), ) CAMBIOS_CHOICES = ( ('No hubo cambios', 'No hubo cambios'), ('Hubo cambios', 'Hubo cambios'), ) class Cliente(models.Model): fecha = models.DateTimeField(db_column='Fecha') # Field name made lowercase. vencimiento = models.DateTimeField(db_column='Vencimiento') # Field name made lowercase. saldo = models.FloatField(db_column='Saldo') # Field name made lowercase. comprobante = models.TextField(db_column='Comprobante') # Field name made lowercase. corredor = models.TextField(db_column='Corredor') # Field name made lowercase. grupo = models.TextField(db_column='Grupo') # … -
What can i use to embbed video conferencing in my Django website?
How can I add video conferencing and audio calls to my Django website? I have seen a lot of people talking about agora but I don't have tried it.is it better? -
Django form with dynamic number of items depending on other model
I'm trying to generate a dynamic form for the models below (some fields removed for brevity): class BreakfastOption(CreatedUpdatedByMixin, TimeStampedModel): """Option for breakfast, e.g. white bread, brown bread, tea, coffee""" name = models.CharField(max_length=30, unique=True) BREAKFAST_CATEGORY_CHOICE = ( ('food_week', 'Food during week'), ('food_weekend', 'Food during weekend'), ('drinks', 'Drinks'), ) category = models.CharField(max_length=32, choices=BREAKFAST_CATEGORY_CHOICE, ) class BreakfastOptionChoice(CreatedUpdatedByMixin, TimeStampedModel): """Option for breakfast along with its desired quantity, e.g. 2 slices of white bread and one tea""" breakfast_option = models.ForeignKey(BreakfastOption, on_delete=models.CASCADE) quantity = models.PositiveSmallIntegerField() class BreakfastPreference(CreatedUpdatedByMixin, TimeStampedModel): """Person's choice for breakfast, e.g. 2 slices of white bread and 1 tea, along with comments""" person = models.ForeignKey(Person, on_delete=models.CASCADE) start_date = models.DateField(default=datetime.date.today) # Used for tracking changes choices = models.ManyToManyField(BreakfastOptionChoice) comments = models.TextField(blank=True, null=True) What I'd like to have is a form for BreakfastPreference where the user can see the whole list of available BreakfastOptions (which are about 8) and can enter a quantity for those, along with overall comments. Example form: Person: (prefilled through URL) "White bread slices" quantity: 2 "Brown bread slices" quantity: 0 "Tea" quantity: 1 "Coffee" quantity: 0 Comments: person wants breakfast as early as possible In the above example, rows 2 to 5 are dynamically generated (i.e. there could be 4, but … -
How to override id field Django model
I'm looking for way to override id field mb with models.AutoField or something like that But the main problem that i want to have specific id field For example: I want id field for user to start with number 0 and after that it might contains number or specific letters and this id will look like this : 0123456ABC and all of this should be unique How can i do that? Should i override models.AutoField? models.py class User(models.Model): id = models.AutoFields() user/0123456ABC -
Paypal standard checkout and Django/Python
I am trying to integrate paypal standard checkout, i have imported paypalrestsdk, I have my correct paypal client id and secret, but I keep getting an error returned: if order.create(): ^^^^^^^^^^^^^^ TypeError: 'NoneType' object is not callable I have done some debugging and this is what gets returned into console: Transaction: {'amount': {'value': '10.00', 'currency_code': 'USD'}, 'description': 'My awesome product'} Order: {'intent': 'CAPTURE', 'purchase_units': [{'amount': {'currency_code': 'USD', 'value': '10.00'}, 'description': 'My awesome product'}]} Internal Server Error: /create_order/ here are my views and scripts: def create_order(request): # Get the transaction details from the client-side transaction = json.loads(request.body) print('Transaction:', transaction) # Create a new PayPal order order = paypalrestsdk.Order({ "intent": "CAPTURE", "purchase_units": [{ "amount": { "currency_code": transaction['amount']['currency_code'], "value": transaction['amount']['value'] }, "description": transaction['description'] }] }) print('Order:', order) if order.create(): # Return the PayPal order ID to the client-side return JsonResponse({"orderID": order.id}) else: # Return an error message to the client-side error_dict = {"error": str(order.error)} return JsonResponse(error_dict, status=400) def capture_payment(request): # Get the PayPal order ID from the client-side order_id = json.loads(request.body)['orderID'] # Capture the PayPal payment order = paypalrestsdk.Order.find(order_id) if order and order.status == "CREATED": capture = paypalrestsdk.Capture({ "amount": { "currency_code": order.purchase_units[0].amount.currency_code, "value": order.purchase_units[0].amount.value } }) if capture.create(order_id): # Return a success message … -
problem in django render partial, i install render partial but i still have an error message
i have install django-render-partial bay pip, and see the success message, but in the settings.py on INSTALL_APPS, i cant add 'django-render-partial' and i got an error message that is : "ModuleNotFoundError: No module named 'django-render-partial'". how i can fix this problem?enter image description here i want that error message disappear and i can use render partial in the project. plz help me ❤️ -
(Django) How to change admin site filtering panel options?
I'm trying to set a filter on the Seller model's admin page using the rate field, but there's a slight issue. the rate field can have a range of: -1 + (0, 5] I want the filter panel to have 6 values, each corresponding to a rate above or equal to the corresponding number (-1, 1, 2, 3, 4, 5) at the moment it looks like this, How can I achieve my goal? models.py: class Seller(models.Model): """ A model for the sellers of the Product model, connected to which with a ForeignKey """ name = models.CharField(max_length=255, blank=False, unique=True) description = models.TextField(max_length=1275, blank=False) join_date = models.DateTimeField( auto_now_add=True, validators=[validate_date_now]) rate = models.FloatField(default=-1) logo = models.ImageField(upload_to=get_upload_path, blank=False) sale_count = models.IntegerField(default=0) def __str__(self) -> str: return str(self.name) admin.py: class SellerAdmin(admin.ModelAdmin): fieldsets = ( (None, { 'fields': ( 'join_date', 'name', 'description', ), }), ('Advanced information', { 'fields': ( 'sale_count', 'rate', 'logo', ) }) ) list_display = ('name', 'join_date', 'sale_count', 'rate') list_filter = ('join_date', 'rate') search_fields = ('name',) readonly_fields = ('join_date', 'rate', 'sale_count') -
"GET /static/admin/css/fonts.css HTTP/1.1" 404 1816 [closed]
my django said I've this error, how can I fix it? (I'm new to this) I search around the web browser can't find the answer -
Django query on a link table generated from a many to many relashionship
Here is an example of a part of a models.py file that manages recipes and ingredients: class Ingredient(models.Model): name = name = models.CharField(max_length=200) class Recipe(models.Model): name = name = models.CharField(max_length=200) ingredients = models.ManyToManyField(Ingredient) I heard that Django will automatically create a link table using the name of the app, then the referencing model and the model being referenced, all in lower case. Let's say that the app in my example is called cookbook then the name of the linked table would be cookbook_recipe_ingredient, am I right so far? So, let's suppose I now want to query this linked table from some sort of script at the bottom of the models.py file, to make automated treatments in the database. In this case, it would be to list all recipes containing peanuts. If it was an SQL database, a simple select distinct recipe from cookbook_recipe_ingredient where ingredient = 'peanut' What would be the Django way of making such a query on such a link table? -
Django Rest Framework, filter by name
I'm trying to create a filter by username, but django nonstop requires id from me. What is repair here? class FavoriteList(generics.ListCreateAPIView): permission_classes = [permissions.IsAuthenticatedOrReadOnly, IsCurrentUserOwnerOrHidden] queryset = Favorite.objects.all() serializer_class = FavoritesSerializer name = 'favorite-list' def perform_create(self, serializer): serializer.save(owner=self.request.user) def filter_queryset(self, queryset): owner_name = self.request.query_params.get('owner', None) if owner_name is not None: queryset = queryset.filter(owner=owner_name) return queryset localhost/favorite?owner=1 is working but loclahost/favorite?owner=admin don't -
Combine several "context"-Blocks in final return-clause of a view
Hiho, i've searched for this and found simliar topics but none of them gave me an answer that seems helpful....or I searched for the wrong terms maybe. Right now I wonder, wether you can optionally combine the context of a "return render...." command in a Django-View. As Django propagates a "Do-Not_Repeat-Yourself" philosophy, I would like to change the following code to shorten it (The several if-clauses have to do with role-rights stuff....): def show(request): now_day = datetime.date.today() current_user = request.user if request.method == 'GET': if view_self(current_user) == True and more_rights(current_user) == False: if Employees.objects.filter(employee_number=current_user).exists(): context = {'names': Employees.objects.filter(employee_number=current_user)} else: context = {'info': "Für sie existiert (noch) kein Datensatz in dieser Datenbank"} else: context = {'names': Employees.objects.all().order_by('last_name').values()} return render(request, 'show.html', context) else: if view_self(current_user) == True and more_rights(current_user) == False: if request.POST['id'] == 'Mitarbeiter auswählen...': context = { 'names': Employees.objects.filter(employee_number=current_user), 'info': "Bitte treffen Sie zuerst eine Auswahl" } else: employee = request.POST['id'] context = { 'names': Employees.objects.filter(employee_number=current_user), 'entries': Employees.objects.filter(id=request.POST['id']), 'work_conditions': Employment.objects.filter(employee_id=request.POST['id']), 'functions': Functions.objects.filter(employee__functions=request.POST['id']).order_by('function'), 'fieldsoa': FieldsOfActivity.objects.filter(employee__fieldsofactivity=request.POST['id']).order_by('field_of_activity'), 'missions': Foreign_Missions.objects.filter(employee_id=request.POST['id']).order_by('-begin'), 'examinations': Examinations.objects.filter(employee_id=request.POST['id']).order_by('-date'), 'total_duration_days': Foreign_Missions.objects.total_duration_days(employee), 'today': now_day, 'special_header': "Datensätze anzeigen" } elif request.POST['id'] == 'Mitarbeiter auswählen...': context = { 'names': Employees.objects.all().order_by('last_name').values(), 'info': "Bitte treffen Sie zuerst eine Auswahl" } elif 'id' in request.POST: employee = … -
Why doesnt switching between templates work in django?
I want to switch between two templates using render in the same function. It worked with one project, but not with this one. I'm going mental. It's about a math quiz, where you can choose between level 1 and level 3. after POST it should render a new html where i can make the layout, but it simply doesnt switch to layout.html index.html <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> {% load static %} <link rel="stylesheet" href="{% static 'css/style.css' %}"> <title>Math Quiz</title> </head> <body> <p class="title">Math Quiz</p> <div class="box"> <button type="submit" onclick="lvl(1)">Level 1</button><br><br> <button type="submit" onclick="lvl(2)">Level 2</button><br><br> <button type="submit" onclick="lvl(3)">Level 3</button> <script> function lvl(num) { fetch("",{ method: "POST", headers: { 'Content-Type': 'application/json', 'X-CSRFToken': '{{ csrf_token }}' // Include the CSRF token in the headers }, body: JSON.stringify({ "num": num }) }) }; </script> </div> </body> </html> layout.html <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> {% load static %} <link rel="stylesheet" href="{% static 'css/style.css' %}"> <title>Math Quiz</title> </head> <body> <p class="title">Math Quiz2</p> <div class="box"> <form method="POST"> <p>{{ quiz }}</p> </form> </div> </body> </html> views.py from django.shortcuts import render import json import random # Create your views here. … -
how to delete an file after sending it to user as file response
I'm trying to send a file to user as file response to the client. after user downloaded it successfully, I want to delete it from the server. for example i downloaded a video file to server into a temp directory and giving it as response to user . then i wanna delete it .. i used temp file to save video, but the directory is not deleted after using the file but when i try to delete that file using add_post_render_callback() in django and @after_this_request decorator in flask and many more. in every case i get error because either the file will be deleted before repose ( file not found - on file response ) or the file is being used by file response so it cannot be used . i also tried multi threading res =request.POST['res'] video_url=request.POST['link'] # Create a temporary directory within the Flask project root directory temp_dir = tempfile.mkdtemp(dir= BASE_DIR / 'temp') # Fetch the YouTube video using pytube yt = YouTube(video_url) stream = yt.streams.filter(mime_type="video/mp4",resolution=res).first() video_path=stream.download(temp_dir) def callback(): shutil.rmtree(temp_dir) response = FileResponse(open(video_path, 'rb'), as_attachment=True, filename='video.mp4') response.add_post_render_callback(callback) return response -
How to automaticly add slugs to the new db objects?
I am using an external admin panel that is not connected to Django(but connected to the postgresql db), and as a result, when I add a new Work object through the admin, it does not automatically add a slug. Is there a way to automatically check when a new object is created in the database and add a slug to it? Below is the code that I am currently using to add slugs: def save(self, *args, **kwargs): if not self.pk: slug_title = translit(self.ukrainian_title, 'uk', reversed=True) self.slug = slugify(slug_title) while Work.objects.filter(slug=self.slug).exists(): self.slug = f"{slugify(slug_title)}-{get_random_string(length=4)}" super().save(*args, **kwargs) And it's working perfectly, but with django default admin, not with the external one. Would appreciate any help -
Gerador de formulario django [closed]
bom dia! Sou novo em programação e estou estudando Django. Gostaria de montar um projeto que receba campos personalizados pelo usuario no formulario, como o Google forms. Mas nao encontrei nada sobre o assunto. Caso alguém possa me apontar um direcionamento agradeço fiz varias buscas e nao encontrei nada atual ou implementavel -
error while adding data in ManyToManyField model
Here assignment Model has ManyToManyField with Tags but when I try to insert data using serializers I got an empty list [], in tags fields here is my serializers.py: from rest_framework import serializers from assignment.models import ( Assignment, Tag, ) class AssignmentSerializer(serializers.ModelSerializer): """Serializer for Assignment.""" class Meta: model = Assignment fields = ["id", "name", "tags", "last_updated_by", "assignment_data"] read_only_fields = ["id"] def create(self, validated_data): """Create an Assignment.""" tags_data = validated_data.pop("tags", []) instance = Assignment.objects.create(**validated_data) for tag_name in tags_data: created = Tag.objects.get_or_create(name=tag_name) instance.tags = created instance.save() return instance I am sending this value: { "name": "demo assignment", "tags": ["demo"], "last_updated_by": "user1", "assignment_data": { "hello": "Hello world 2" } } please let me know if you require any other information -
Having trouble with bulk_create()-ing models in Django
The first problem is that I have a Question model and a Tags model, which share a ManyToMany relationship and Django doesn't allow direct assignment to them during creation. So the only solution I could find is to create the questions and then manually assign the tags to them, creating hundreds of slow queries. def handle(self, *args, **options): user_profiles = list(Profile.objects.all()) if not user_profiles: print("No users found to create questions") return tags = list(Tag.objects.all()) new_questions = [Question( title=random_sentence(12, 12), content=random_text(12, 12, 12), author=random.choice(user_profiles), ) for _ in range(options['questions_num'][0])] new_questions = Question.objects.bulk_create(new_questions) for question in new_questions: question.tags.set([random.choice(tags) for _ in range(random.randint(1, 4))]) The second problem is about bulk-creating users. I have a Profile model associated with the default Django User model with some additional fields, so I have to create both. But I have to keep in mind the unique constraint of each user and that would mean manually checking if they exist for each of them. Ignoring conflicts during bulk_create means that all the objects won't have primary keys and will be useless to me. def handle(self, *args, **options): username_length = User._meta.get_field('username').max_length password_length = User._meta.get_field('password').max_length email_length = User._meta.get_field('email').max_length - len('@mail.ru') try: users = [User( username=random_word(username_length), password=random_word(password_length), email=f"{random_word(email_length)}@mail.ru", ) for _ …