Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django update m2m objects on save
I have a m-2-m rel and i want to update the rel B after any rel A is added via the admin page. Here the details: I have 2 models, Match (rel A) and Player (rel B). I want to update Player.matches_played eveytime a new Match with that player in Match.team1 or Match.team2 is added. How can i achieve this??? the models class Match(models.Model): data=models.DateField(auto_now_add=False,auto_now=False) team1=models.ManyToManyField('players.Player',related_name='team_1') team2=models.ManyToManyField('players.Player',related_name='team_2') score_team1=models.IntegerField(validators=[MinValueValidator(0)]) score_team2=models.IntegerField(validators=[MinValueValidator(0)]) class Player(models.Model): matches_played= models.IntegerField(validators=[MinValueValidator(0)], default=0) I tried signals but in post_save signal {instance.team1} or instance.team1.all() return an empty QuerySet which i believe is correct as the M2M rel is saved later. Then i tried m2m_changed but that signal is not fired with a save via the admin page. What am i missing? @receiver(post_save, sender=Match, dispatch_uid="update_player_game_count") def update_player_games(sender, instance, created, **kwargs): print(f'created {instance.pk}') print(f'created {instance.team1}') print(f'created {instance.team2}') print(f'created {instance.score_team1}') print(instance.team1.all()) @receiver(m2m_changed, sender=Match, dispatch_uid="update_player_game_count") def update_player_game(sender, instance, created, action, **kwargs): print(action) if action == 'post_add': print(action) Thank you very much for you help an alternative which i thought about is to retrieve the data via a property in Player for instance like this, but i think, from a performance point of view, is better to update rows every time a match is added … -
Media not shown on django nginx host
I am currently working on a django project which I deployed to a digitalocean droplet with nginx. The website works, including the staticfiles. After looking at my error.log i saw that it was a permission problem: 2024/04/27 18:58:19 [error] 130139#130139: *194 open() "/home/project/project/media/gallery/IMG_9510.jpeg" failed (13: Permission denied) And when excecuting the namei command, this is the response: root@host:~# namei -l /home/project/project/media/gallery/IMG_9510.jpeg f: /home/refugium/refugium/media/gallery/IMG_9510.jpeg drwxr-xr-x root root / drwxr-xr-x root root home drwxr-x--- project_user project_user project drwxrwxr-x project_user project_user project drwxr-xr-x www-data www-data media drwxr-xr-x www-data www-data gallery -rwxr-xr-x www-data www-data IMG_9510.jpeg So the permissions seem to be fine. For the last check I shortly changed the user in my nginx.conf to root. After that it worked. Did I miss anything? This is my file in sites-available: server { listen 80; server_name refugium-romontberg.ch; location = /favicon.ico { access_log off; log_not_found off; } location /media/ { alias /home/refugium/refugium/media/; } location /static/ { alias /home/refugium/refugium/staticfiles/; } location / { client_max_body_size 200M; include proxy_params; proxy_pass http://unix:/run/gunicorn.sock; } } Thanks -
Django unit test fixing database row id
from django.test import TestCase class DefTests(TestCase): def setUp(self): # first made the label UserType(label="mylabel").save() ## UserType is model object, and I made the first row , the id is supposed to be 1 def test_my(self): u = UserType.objects.get(id=1) # UserType.DoesNotExis error I guess in test mode real insert is not executed, so id is not fixed. Am I correct? Then, Is there any way to fix the id in advance before doing test_****? -
Django Rest Framework serializer simultaneously request bug
i have one view with my basics config class base_view(LoginRequiredMixin, PermissionRequiredMixin): filter_backends = [SearchFilter] pagination_class = generic_pagination permission_required = '' # assigned at each final view (children) raise_exception = True # avoid redirecting to backend login fields = '__all__'# by default brings all fields aliases = [] # placeholder to avoid error as some views will not need aliases def handle_no_permission(self): if self.request.user.is_authenticated: # If the user is authenticated, but still lacks permission, return a JSON response indicating access denied. return JsonResponse({'detail': 'Permission Required'}, status=403) else: # If the user is not authenticated, return a JSON response indicating login required. return JsonResponse({'detail': 'Login Required'}, status=401) def get_serializer_class(self): self.serializer_class = generic_serializer self.serializer_class.Meta.model = self.model self.serializer_class.Meta.fields = self.fields self.serializer_class.Meta.aliases = self.aliases return self.serializer_class ### filter all querysets by company and organization + ordering def get_queryset(self): if self.fields == '__all__': queryset = self.model.objects.all() else: queryset = self.model.objects.only(*self.fields) ### gets user company/organization or FORCES specific company/organization (ADMIN ONLY!) if (self.request.query_params.get('id_com') is not None) and (self.request.user.id==id_admin): queryset = queryset.filter(id_company_fk=self.request.query_params.get('id_com')) if self.request.query_params.get('id_org') is not None: queryset = queryset.filter(id_organization_fk__in = self.request.query_params.get('id_org').split(',')) else: queryset = queryset.filter(id_company_fk=self.request.user.profile.id_company_fk) ### below: filters by organization(s) IF one is specified in user's profile AND if field exists on model if (self.request.user.profile.id_organization_fk is not … -
django - how to distinguish code is run by manage.py or but http server
I customized AppConfig in django to start some processes needed for the main application as described in the django documentation. In the usual initialization process, the ready method is only called once by Django. But in some corner cases, particularly in tests which are fiddling with installed applications, ready might be called more than once. In that case, either write idempotent methods, or put a flag on your AppConfig classes to prevent rerunning code which should be executed exactly one time. Two questions: in my experience the ready() method is alwasys called at least twice even if it just print an hello message. How can I add the flag pointed out in the documentation? I don't want the processes start when I run manage.py commands (ex. to migrate). How can I manage this in the code? -
using my trained model in the views, don't allow me to render the new return valus
it takes a while to load all the data into the new df_with_ṕredictions, my problem is how can I render the new table with those predictions in a template : def home(request): df = None df_with_predictions = None error_message = None api_key = None column_name = None predictions_html = "" # Initialize an empty string for the DataFrame HTML if request.method == 'POST': api_key = request.POST.get('api_key_input', '') column_name = request.POST.get('column_name', '') file = request.FILES.get('file') if file: try: file_ext = file.name.split(".")[-1] if file_ext == "csv": df = pd.read_csv(file) elif file_ext == "xlsx": df = pd.read_excel(file) if df is not None: x_new = get_embeddings(df, column_name, api_key) if x_new is not None: new_predictions = classify_comments(x_new) df_with_predictions = df.copy() df_with_predictions['Clasificación_gpt_'] = new_predictions print("File has been processed and predictions are added. in home") print(df_with_predictions) # Convert DataFrame to HTML predictions_html = df_with_predictions.to_html(classes="table table-striped", index=False) except Exception as e: error_message = str(e) context = { 'api_key': api_key, 'column_name': column_name, 'predictions_html': predictions_html, # Pass the HTML to the template 'error_message': error_message } return render(request, "home.html", context) I tried having al the variables in one post for manipulated in the home views, but I am still having troubles -
Enabling cache and images not loading in django?
If you enable the cache: @cache_page(20, key_prefix='index_page') def index(request): post_list = Post.objects.order_by('-pub_date').all() paginator = Paginator(post_list, 10) page_number = request.GET.get('page') page = paginator.get_page(page_number) return render(request, "index.html", {'page': page, 'paginator': paginator}) When I create a new post, I can no longer upload an image. @login_required def post_edit(request, username, post_id): profile = get_object_or_404(User, username=username) post = get_object_or_404(Post, pk=post_id, author__username=username) if request.user != post.author: return redirect('post', username=username, post_id=post_id) form = PostForm(request.POST or None, files=request.FILES or None, instance=post) if form.is_valid(): form.save() return redirect('post', username=username, post_id=post_id) return render(request, 'post_new.html', {'form': form, 'post': post}) How can I fix this so that it was possible to download pictures and use the cache? -
ImproperlyConfigured: settings.DATABASES is improperly configured. Please supply the ENGINE value cant migrate python file
I am not able to migrate my changes. when i run python manage.py runserver - Full Traceback Traceback (most recent call last): File "C:\Users\kshitijb\Desktop\Income-Expense-Tracker\manage.py", line 22, in main() File "C:\Users\kshitijb\Desktop\Income-Expense-Tracker\manage.py", line 18, in main execute_from_command_line(sys.argv) File "C:\Users\kshitijb\Desktop\Income-Expense-Tracker\env\Lib\site-packages\django\core\management_init_.py", line 442, in execute_from_command_line utility.execute() File "C:\Users\kshitijb\Desktop\Income-Expense-Tracker\env\Lib\site-packages\django\core\management_init_.py", line 436, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "C:\Users\kshitijb\Desktop\Income-Expense-Tracker\env\Lib\site-packages\django\core\management\base.py", line 413, in run_from_argv self.execute(*args, **cmd_options) File "C:\Users\kshitijb\Desktop\Income-Expense-Tracker\env\Lib\site-packages\django\core\management\base.py", line 459, in execute output = self.handle(*args, **options) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\kshitijb\Desktop\Income-Expense-Tracker\env\Lib\site-packages\django\core\management\base.py", line 107, in wrapper res = handle_func(*args, **kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\kshitijb\Desktop\Income-Expense-Tracker\env\Lib\site-packages\django\core\management\commands\migrate.py", line 117, in handle executor = MigrationExecutor(connection, self.migration_progress_callback) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\kshitijb\Desktop\Income-Expense-Tracker\env\Lib\site-packages\django\db\migrations\executor.py", line 18, in init self.loader = MigrationLoader(self.connection) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\kshitijb\Desktop\Income-Expense-Tracker\env\Lib\site-packages\django\db\migrations\loader.py", line 58, in init self.build_graph() File "C:\Users\kshitijb\Desktop\Income-Expense-Tracker\env\Lib\site-packages\django\db\migrations\loader.py", line 235, in build_graph self.applied_migrations = recorder.applied_migrations() ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\kshitijb\Desktop\Income-Expense-Tracker\env\Lib\site-packages\django\db\migrations\recorder.py", line 89, in applied_migrations if self.has_table(): ^^^^^^^^^^^^^^^^ File "C:\Users\kshitijb\Desktop\Income-Expense-Tracker\env\Lib\site-packages\django\db\migrations\recorder.py", line 63, in has_table with self.connection.cursor() as cursor: ^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\kshitijb\Desktop\Income-Expense-Tracker\env\Lib\site-packages\django\utils\asyncio.py", line 26, in inner return func(*args, **kwargs) ^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\kshitijb\Desktop\Income-Expense-Tracker\env\Lib\site-packages\django\db\backends\base\base.py", line 316, in cursor return self._cursor() ^^^^^^^^^^^^^^ File "C:\Users\kshitijb\Desktop\Income-Expense-Tracker\env\Lib\site-packages\django\db\backends\dummy\base.py", line 20, in complain raise ImproperlyConfigured( django.core.exceptions.ImproperlyConfigured: settings.DATABASES is improperly configured. Please supply the ENGINE value. Check settings documentation for more details. seetings.py DB_NAME = os.environ.get("POSTGRES_DB") #database name DB_USER_PASSWORD = os.environ.get("POSTGRES_PASSWORD") # database user password DB_USER = os.environ.get("POSTGRES_USER") # database username DB_HOST … -
CSS is not visible
I'm working on a project using Django. I imported HTML files and created a Base HTML. I placed CSS and images in a folder named 'static' and imported them, but the CSS is not appearing on the site, only the HTML. Would you like me to share the code? I try to change something on setting.py Nothing yet. I didn't want to change it without help from someone. -
Django Form's HiddenInput does not save initial value
I have a simple form with two HiddenInputs. Submitted form does not save initial values for hidden fields. What am I missing? forms.py class TestForm(forms.Form): foo = forms.CharField(required=False, initial="Foo") bar = forms.CharField(required=False, initial="Bar", widget=forms.HiddenInput()) is_true = forms.BooleanField(required=False, initial=True, widget=forms.HiddenInput()) views.py def test_view(request): test_form = TestForm() if request.method == "POST": test_form = TestForm(request.POST) if test_form.is_valid(): print(test_form.cleaned_data) return render(request, "test.html", {"test_form": test_form}) output {'foo': 'Foo', 'bar': '', 'is_true': False} How can i get presettled values for hidden fields after form submit? {'foo': 'Foo', 'bar': 'bar', 'is_true': True} -
Getting error while running Django app on apache2 server about GOOGLE_CLOUD_PROJECT
I am facing an issue while deploying my Django app on apache2 sever. Project ID is required to access Cloud Messaging service. Either set the projectId option, or use service account credentials. Alternatively, set the GOOGLE_CLOUD_PROJECT environment variable. I have declared these in my setting.py GOOGLE_APPLICATION_CREDENTIALS = '<path to json>' GOOGLE_CLOUD_PROJECT = '<project id>' FIREBASE_APP = initialize_app() I tried setting environment variable export GOOGLE_CLOUD_PROJECT= When I run my project ./manage.py runserver then it is working fine. -
Create Razorpay Order in my Django DRF project gives 401 Error. "Authentication credentials were not provided."
Im trying to create a view where we create an order through razorpay, but continuously getting 401 error despite the keyId and KeySecret being correct. Even postman and curl gives the same error. I have tried removing the authentication, adding authentication through postman etc, but the issue persists. The Key works for razorpay's global API correctly, but the error is only in my function. Any help would be welcome thanks curl -X POST -H "Content-Type: application/json" -H "Authorization: Basic cnpwX3Rlc3RfNGZTSXNRaWdoeTZnU3o6Y1pZT3pvbnRWOFlEM1V1bzFneVlYalVF" -d "{\"amount\": 10000, \"currency\": \"INR\", \"receipt\": \"order_receipt\"}" http://127.0.0.1:8000/api/orders/create-razorpay-order/ {"detail":"Authentication credentials were not provided."} path('create-razorpay-order/', views.create_razorpay_order, name="create_razorpay_order"), def create_razorpay_order(request): razorpay_key = 'KEYID' razorpay_secret = 'RAZORPAYKEYSECRET' # Concatenating the API key and secret with a colon key_id_secret = f'{razorpay_key}:{razorpay_secret}' # Base64 encode the concatenated string base64_encoded_key_id_secret = base64.b64encode(key_id_secret.encode()).decode() # Endpoint for creating an order on Razorpay's server razorpay_order_url = 'https://api.razorpay.com/v1/orders' # Amount in paise (e.g., 10000 represents ₹100.00) amount = 10000 # Data to be sent in the request body data = { 'amount': amount, 'currency': 'INR', # Currency code (e.g., INR for Indian Rupees) 'receipt': 'order_receipt1', # Unique identifier for the order (optional) } # Headers for the request headers = { 'Content-Type': 'application/json', 'Authorization': f'Basic {base64_encoded_key_id_secret}', } # Make a … -
Django render a view depending geolocation from the browser
I'm trying to load my home page according to the geolocation given by the browser, if the coordinates are ok, I load a list of airports around these coordinates, otherwise I load all airports. However, I can't manage this between GET & POST requests. Each time I get all the airports in the page. In fact when the view is loaded (by the GET request) all airport are displayed, after when the page is entirely loaded the POST event is raised with the GPS information. So the list of airports around location is performed but the rendering is always wrong. urls.py urlpatterns = [ path('admin/', admin.site.urls), path('',views.home_view), views.py def home_view(request): x_forwarded_for = request.META.get('HTTP_X_FORWARDED_FOR') if x_forwarded_for: ip = x_forwarded_for.split(',')[0] else: ip = request.META.get('REMOTE_ADDR') if request.method == 'POST': Latitude = float(request.POST.get('latitude')) Longitude = float(request.POST.get('longitude')) context = aviationweatherapi.getStationInfo(Latitude,Longitude) print ("Get airports list around current GPS location") else: #The request is GET context = aviationweatherapi.getStationInfo(None, None) print ("Get all airports") context.update({'IP':ip}) return render(request,'acceuil.html',context) template_Base.html (base of the acceuil.html) <body> {% csrf_token %} {% block contenu %} {% endblock %} <script src="https://code.jquery.com/jquery-3.6.0.js"></script> <script src="https://code.jquery.com/ui/1.13.2/jquery-ui.js"></script> <script> const findLoc = () => { const success = (position) => { const latitude = position.coords.latitude; const longitude = position.coords.longitude; … -
How to set custom JWT in django using dj-rest-auth
I have setup a backend JWT authentication system using django, dj-rest-auth and simpleJWT. Currently, the dj-rest-auth is setting default JWT in the response cookies. To use custom cookies, I have to use simpleJWT's /token and /token/refresh urls. So, while testing in postman or swagger, I'm not getting the custom JWTs neither in the response body nor in the cookies(except the default ones provided by dj-rest-auth). Is there a way around so that I can receive those custom JWTs as cookies or response body? I am also using social authentication so those tokens have to be present in the response JWTs as well. My urls.py file urlpatterns = [ path('', include(router.urls)), path('token/', TokenObtainPairView.as_view(), name='token_obtain_pair'), path('token/refresh/', TokenRefreshView.as_view(), name='token_refresh'), path('users/', include('dj_rest_auth.urls')), path('users/registration/', CustomRegisterView.as_view(), name='custom_rest_register'), ] serializer.py class EnrichedTokenPairSerializer(TokenObtainPairSerializer): @classmethod def get_token(cls, user): token = super().get_token(user) // custom token logic return token` I am using Django>=5.0.2 django-allauth>=0.61.1 djangorestframework>=3.14.0 djangorestframework-simplejwt>=5.2.2 dj-rest-auth>=5.0.2 Any suggestions would be helpful. I have done the authentication using dj-rest-auth and simpleJWT. I have a custom token serializer function to create custom tokens which return from /token url of simpleJWT. But while loggin in through Postman, these custom tokens were not present. I want them to be sent from the server either … -
I keep getting these errors "GET /static/style.css HTTP/1.1" 404 179 , "GET / HTTP/1.1" 200 10881 , Broken pipe from ('127.0.0.1', 57644)
STATIC_URL = '/static/' STATICFILES_DIRS = ((os.path.join(BASE_DIR, 'static')), ) STATIC_ROOT = os.path.join(BASE_DIR, 'files') STATIC FILES_FINDERS = [ > > "django.contrib.staticfiles.finders.FileSystemFinder", > > "django.contrib.staticfiles.finders.AppDirectoriesFinder", > > ] urlpatterns = [ path('admin/', admin.site.urls), path('', views.home, name='home'), path('paintings/', views.paintings, name='paintings'), path('sculptures/', views.sculptures, name='sculptures'), path('engravings/', views.engravings, name='engravings'), path('future_auction/', views.future_auction, name='future_auction'), path('winners/', views.winners, name='winners'), static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) I was trying to deploy my project but when i turned DEBUG = False ALLOWED_HOSTS = ['*'] and run the server,i got these issues -
Django: no access to database from async function
I am writing tests for my Django application using asyncio and running into a database access issue. Here is minimal code that reproduces the error: import pytest from authentication.models import User @pytest.mark.django_db(transaction=True) @pytest.mark.asyncio class TestDatabaseAccess: @pytest.fixture(autouse=True) def _fixture(self): User.objects.create(username='username') async def test_main(self): async def get_user_async(user_id): user = await sync_to_async(User.objects.get)(id=user_id) return user await get_user_async(1) I get error: def execute(self, query, params=None): if params is None: return Database.Cursor.execute(self, query) query = self.convert_query(query) return Database.Cursor.execute(self, query, params) E django.db.utils.OperationalError: no such table: authentication_customuser What am I doing wrong? My fixture works fine and has access to database, I can print all users form there But async test throwing an error. -
Creating two separate models for patient and doctor using Django
I want to create registration as a patient and as a doctor such that when user login my website they get two options(as patient or as doctor).How to achieve this using Django? Registration form has different fields for Doctor and Patient. I want code.I'm not able to understand relationship.Also urls.py for this project. -
Django Ñ problem? ValueError: source code string cannot contain null bytes
I'm working on Django and connecting to a remote SQL Server database. I managed to make the connection to the database using the MSSQL engine, but when I run inspectdb, the generated file contains errors due to the character "Ñ", in the file they appear as ±. So when I try to run the server, I get the following error: ValueError: source code string cannot contain null bytes. refering to the generated file with inspectdb I suspect that the problem is related to the database encoded in Modern_Spanish_CI_AS and also Ñ character is causing trouble. So far, I've tried the following: In settings.py, in database options: 'unicode_results': True Also, 'extra_params': 'ClientCharset=utf8' Modifying in base.py: mssql: unicode_results = options.get('unicode_results', True) Some less elegant solutions like opening the generated file with Notepad and saving it in UTF-8 or ISO 8859-1 -
When posting on django website it posts it to a different page
Making a website that has a forum for text posts and a greenhouse page for images, when I try to post on the forum page it posts it to the greenhouse page, and when i try to add a comment on a post in the forum page I get: PlantPost matching query does not exist. Request Method: POST Request URL: http://127.0.0.1:8000/greenhouse/create_comment/1/ Django Version: 5.0.4 Exception Type: DoesNotExist Exception Value: PlantPost matching query does not exist. Exception Location: C:\Users\hurle\OneDrive\Documents\Desktop\profile_env\Lib\site-packages\django\db\models\query.py, line 649, in get Raised during: greenhouse.views.create_comment Python Executable: C:\Users\hurle\OneDrive\Documents\Desktop\profile_env\Scripts\python.exe Python Version: 3.12.1 Python Path: ['C:\\Users\\hurle\\OneDrive\\Documents\\Desktop\\bloomhub4', 'C:\\Users\\hurle\\AppData\\Local\\Programs\\Python\\Python312\\python312.zip', 'C:\\Users\\hurle\\AppData\\Local\\Programs\\Python\\Python312\\DLLs', 'C:\\Users\\hurle\\AppData\\Local\\Programs\\Python\\Python312\\Lib', 'C:\\Users\\hurle\\AppData\\Local\\Programs\\Python\\Python312', 'C:\\Users\\hurle\\OneDrive\\Documents\\Desktop\\profile_env', 'C:\\Users\\hurle\\OneDrive\\Documents\\Desktop\\profile_env\\Lib\\site-packages'] forum create_comment.html {% extends "home.html" %} {% block content %} <h2>Add Comment</h2> <form action="{% url 'forum:create_comment' post.id %}" method="post"> {% csrf_token %} {{ form.as_p }} <button type="submit">Submit</button> </form> {% endblock %}``` **forum create_post.html** ```{% extends "home.html" %} {% block content %} <h2>Create Post</h2> <form action="{% url 'create_post' %}" method="post" enctype="multipart/form-data"> {% csrf_token %} {{ form.as_p }} <button type="submit">Submit</button> </form> {% endblock %} forum models.py from django.db import models from django.contrib.auth.models import User class Post(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) content = models.TextField() image = models.ImageField(upload_to="forum_images/", null=True, blank=True) created_at = models.DateTimeField(auto_now_add=True) class Comment(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) post = models.ForeignKey(Post, on_delete=models.CASCADE) content … -
Can I add the controller part of the MVC pattern to the MTV pattern in Django?
I'm trying to develop a multiplayer web game using Django. I understand that in Django's MTV Pattern, the view part takes on the role of the controller. But the view part needs a user in the frontend who accesses the website in order to be able to carry out actions. But in my WebGame there are also actions that need to be executed in the background, which need to be executed at certain times without any user in the frontend. So can I insert a folder in my Django code with the controller classes and specify when which function should be executed regularly? If I'm on the wrong path when it comes to solving my problem, I'm of course also interested in alternative suggestions. I watched a few videos and read a few books, but I couldn't find anything that really matched my problem. -
Calling python package by package name
I want to call my local package utility by its name like in Django django-admin. It has structure like: utility-name [command] I've found the method of calling utility using __ main __.py. Structure of using this method is: python -m myappname. But it isn't what I wanted. So how I can use structure of calling like in django-admin? I'm junior programmer so if this information isn't enough u may ask questions -
Why do I get a Integrity Error when using this code in Django?
I am having issues while learning about SQLite databases in Django. I am trying to check if a specific url is already in the database, but I keep getting a Integrity Error. this is the code that is supposed to check if it is already in the database: if not Songs.objects.filter(tidal_url=song_url): new = Songs(name=name, artist=artist, tidal_url=song_url) new.save() These are my models: from django.db import models from django.contrib.auth.models import User # Create your models here. class Songs(models.Model): name = models.CharField(max_length=255) artist = models.CharField(max_length=255) tidal_url = models.CharField(max_length=255, unique=True) class UserDownload(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) song = models.ForeignKey(Songs, on_delete=models.CASCADE) dl_path = models.CharField(max_length=255) Can anyone figure out why this is happening? -
django a filed can not make it althougfh i make makemigrations and migrate
hi i have a filed i cannot make it in database although i make makemigrations and migrte this is models.py ``your text`` class Display(models.Model) : `your text` url=models.URLField(unique=True) `your text` text = models.CharField(max_length=150) `your text` class Display_Data(models.Model) : `your text` displays = models.ManyToManyField(Display,related_name='display_data') `your text` users= models.ForeignKey(UserProfile,on_delete=models.CASCADE,default="1") `your text` choosenum=models.IntegerField() `your text` puplish_date =models.DateTimeField(default=datetime.now) and this is models.py for accounts app `your text`class UserProfile(models.Model): `your text` user=models.OneToOneField(User,on_delete=models.CASCADE) `your text`user_nickname=models.CharField(max_length=150) `your text`nikename_url=models.URLField() `your text`userphoto =models.ImageField(upload_to='imageprofile/%Y/%m/%d/') and this is views.py for display app `your text`def check_url_exists_and_person(url_to_check): `your text`user_info_array = [] `your text`for i in range(1, 6): latest_successful_record = Display_Data.objects.filter(displays__url=url_to_check, choosenum=i).order_by('-puplish_date').first() if latest_successful_record: user_info = { 'user_nickname': latest_successful_record.users.userprofile.nikename, 'url': latest_successful_record.users.userpofile.nikename_url } else: user_info = None user_info_array.append(user_info) return user_info_array i received a mistake from Django 'Unknown column 'display_display_data.users_id' in 'field list'") why database have not a filed user_id although i make it in models.py i make a new database and delete files of migrations in application display and app userprofile and the filed is not create -
I am getting NoReverseMatch error when adding students data in django admin panel
I am a beginner and trying to create a basic college portal. I am getting NoReverseMatch at /admin/api/student/add/ error when adding students data in django-admin panel. urls.py from django.contrib import admin from django.urls import path,include urlpatterns = [ path('admin/',admin.site.urls), path('api/',include('api.urls')), ] admin.py from django.contrib import admin from .models import Student, Instructor, Course, Enrollment @admin.register(Student) class StudentAdmin(admin.ModelAdmin): list_display = ['std_id', 'firstname', 'lastname', 'date_of_birth', 'cgpa'] @admin.register(Course) class CourseAdmin(admin.ModelAdmin): list_display = ['course_id', 'coursename', 'cred_hrs'] @admin.register(Instructor) class InstructorAdmin(admin.ModelAdmin): list_display = ['instructor_id', 'instructor_name'] @admin.register(Enrollment) class EnrollmentAdmin(admin.ModelAdmin): list_display = ['enrollment_id', 'student', 'course', 'instructor'] models.py from django.db import models from django.core.validators import MinValueValidator, MaxValueValidator # Create your models here. class Student(models.Model): std_id = models.CharField(max_length=6,primary_key = True, unique=True , editable=False) firstname = models.CharField(max_length=30) lastname = models.CharField(max_length=30) date_of_birth = models.DateField() cgpa = models.FloatField( validators=[MinValueValidator(0), MaxValueValidator(4)] ) class Course(models.Model): CREDIT_HOURS_CHOICES = [ (1, '1 credit hour'), (2, '2 credit hours'), (3, '3 credit hours'), ] course_id = models.CharField(max_length=6,primary_key = True, unique=True , editable=False) coursename = models.CharField(max_length=100) cred_hrs = models.IntegerField(choices=CREDIT_HOURS_CHOICES) class Instructor(models.Model): instructor_id = models.CharField(max_length=6,primary_key = True, unique=True , editable=False) instructor_name = models.CharField(max_length=100) class Enrollment(models.Model): enrollment_id = models.AutoField(primary_key=True) student = models.ForeignKey(Student, on_delete=models.CASCADE) course = models.ForeignKey(Course, on_delete=models.CASCADE) instructor = models.ForeignKey(Instructor,on_delete = models.CASCADE) I am new to this kind of stuff so yeah... … -
Group by or distinct for django to remove the row which has the duplicate column
I have table like this below Table A ID name score 1 aaa 100 2 bbb 200 3 ccc 300 4 bbb 100 5 kkk 600 6 ccc 300 Now name bbb and ccc is duplicated so, I want to remove then and depict like this, ID name score 1 aaa 100 2 bbb 200 3 ccc 300 5 kkk 600 I found out that django model doesn't have groupby so, I guess need to use annotate or distinct So my idea is like this below, MyModel.objects.annotate(Count('name')) However it doesn't work as I hope. Any help or hint?