Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
ndarray is not C-contiguous what is the error?
ndarray is not C-contiguous Request Method: POST Request URL: http://127.0.0.1:8000/rainfall Django Version: 4.0.4 Exception Type: ValueError Exception Value: ndarray is not C-contiguous -
Django is annotating wrong Count (possibly duplicates?)
I have a model ChatMessage that has a field sender which is a ForeignKey to User model. I'm trying to annotate a number of all the ChatMessage objects that haven't been read (eg. have seen_at__isnull=True). For a given user, there is only one sent message with seen_at__isnull=True but Django returns 11. User.objects.select_related(...).annotate( sent_unread_messages=Count('sent_chat_messages', filter=Q(sent_chat_messages__seen_at__isnull=True))) do you know where is the problem? -
How to associate parent table instance with newly child table instance through foreign keys in Django?
I'm new to Django and reactJS. I'm creating models with foreign key relationships in Django models. But when I send data from React to my Django rest API, it creates the parent table object on the basis of a foreign key value instead of associating it with the existing value. How can I associate with the newly created child instance instead of creating the parent object? I'm searching for the last 2 days but nothing worked for me. What I'm doing wrong? It gives me this response header in my reactJS application: {"store_title":[" store data with this store title already exists."]} My models are: def user_directory_path(instance, filename): # file will be uploaded to MEDIA_ROOT / user_<id>/<filename> return 'user_{0}/{1}'.format(instance.user, filename) class StoreData(models.Model): STATUS=( ('A','Active'), ('P','Pending approval'), ('B','Blocked'), ) store_title=models.CharField(max_length=50,primary_key=True, null=False) tagline=models.CharField(max_length=100,null=False, default='') store_type=models.CharField(max_length=10,null=False, default='') description=models.CharField(max_length=500,null=False, default='') user=models.ForeignKey(User,on_delete=models.CASCADE,null=True) logo_img=models.ImageField(upload_to=user_directory_path, default='') brand_img=models.ImageField(upload_to=user_directory_path, default='') link=models.CharField(max_length=100, default='') date_created=models.DateField(default=timezone.now) status=models.CharField(max_length=20,choices=STATUS,default='A') def __str__(self): return str(self.store_title) class Categories(models.Model): title=models.CharField(max_length=50, default='none') thumbnail_img=models.ImageField(upload_to=user_directory_path, default="") store_title=models.ForeignKey(StoreData, on_delete=models.CASCADE, default='') def __str__(self): return str(self.title) My serializers are: class StoreSerializer(serializers.ModelSerializer): class Meta: model = StoreData fields = '__all__' class CategorySerializer(serializers.ModelSerializer): def __init__(self, data): self.store_title=serializers.SlugRelatedField(queryset=StoreData.objects.filter(pk=data['store_title'])) class Meta: model = Categories fields = '__all__' And my rest API is: @api_view(['POST']) def addCategory(request): serializer=CategorySerializer(data=request.data) if serializer.is_valid(): serializer.save() … -
How to become a profitable full stack developer?
I am a front-end developer. I already know React and Next.js technologues and have done many projects. I want to become a full-stack developer, so what is the right roadmap to achieve the goal. I also would like to know what technologies are in demand on the back-end side including programming languages, frameworks, databases, etc. I would be glad to see your suggestions. -
why company choose web framework to build e-commerce?
I am wondering why some companies use web framework like spring, laravel, django..etc to build e-commerce website while there are good solutions like wordpress, wix..etc thank you -
How much can i earn from selling APIs? [closed]
I'm a collage student learning python and i watched Anía Kubów's video on selling APIs, so i thought it would be a nice way to earn some money on the side without it taking up to much of my study time. I was planing to use flask or django for making APIs, and i was wondering does anyone have any experience with this and can you earn some decent money doing this (by decent i mean not too much, just something to help me get by). And if not does anyone have an idea about some other way for me to earn money from programming without it taking up too much of my time. Thank you. -
Adding a signup option on the far right on HTML
I would like to add a signup button on the far right of my webpage. When ever I try to edit something before the closing header tab it randomly appears in a spot I do not want.. how do I go on and add it correctly? Assume I want to add something as simple as <p align="right"></p><li><a href="/">Sign Up</a></li></p> Eventually what i'll get is enter image description here {% load static %} <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <title>Movies</title> <meta name="viewport" content="width=device-width, initial-scale=1, minimum-scale=1, maximum-scale=1"> <!-- Icon --> <link rel="icon" href="{% static 'img/icon.jpg' %}" type="image/icon type"> <!-- Sign up button --> <!-- Link Swiper's CSS --> <link rel="stylesheet" href="{% static 'css/swiper.min.css' %}"> <link rel="stylesheet" href="{% static 'css/styles.css' %}"> <script src="{% static 'js/jquery-3.1.1.min.js' %}"></script> <script src="{% static 'js/script.js' %}"></script> <!-- Demo styles --> <style> </style> </head> <body> <div class="wrapper"> <header class="header"> <figure class="logo"><a href="/"><img src="{% static 'img/logo.png' %}" alt="Logo"></figure></a> <nav class="menu"> <ul> <li><a href="/">Home</a></li> <li><a>Genres</a> <ul> <li><a href="{% url 'movies:movie_category' 'action' %}">Action</a></li> <li><a href="{% url 'movies:movie_category' 'comedy' %}">Comedy</a></li> <li><a href="{% url 'movies:movie_category' 'drama' %}">Drama</a></li> <li><a href="{% url 'movies:movie_category' 'romance' %}">Romance</a></li> </ul> </li> <li><a>Year</a> <ul> <li><a href="{% url 'movies:movie_year' year=2022 %}">2022</a></li> <li><a href="{% url 'movies:movie_year' year=2021 %}">2021</a></li> <li><a href="{% url 'movies:movie_year' … -
What is the correct way to add dynos to Django/Heroku project?
This is continuation of my previous question: What is the propper way to debug gunicorn? Currently I am having error code=H14 desc="No web processes running" wihch suggests that there are no dynos. I tried to fix this by doing heroku ps:scale web=1, but instead got error: Scaling dynos... ! ▸ Couldn't find that process type (web).. This answer suggests "simple disable/enable through heroku dashboard". However I can't see any way I can do that. Some other possible solutions suggested that the problem is with the Procfile, its location or its content. Here is my Procfile web: gunicorn kauppalista.wsgi --log-file - Here is my folder structure: folder my_project │ requirements.txt │ runtime.txt │ folder .git │ folder my_project-env │ └───folder my_project │ │ folder my_project (main Django app) │ │ folder django app 1 │ │ folder django app 2 │ │ manage.py │ │ Procfile -
several successive answers to a single question on one page (POST request, django)
I'm very news to django and need help for structuring a project. I would like to make a page (one page) which shows the image of a person; the user must recognize the person and write his/her name on a field. The answer gets processed and if it's wrong, the player can try again. I can do it with two pages (choose image, show image, take answer; then show verdict, return). But I can't seem to fathom the structure of the index view for doing it all on the same page. So the page should behave differently if an answer has been given already, or not; if no, it should take a random image, and show it; if yes, it should compare the POST request result to a variable. How do I write this? Here is the views.py : from django.http import HttpResponse from django.template import loader, Context, Template from .models import Mystere, Image, Indice from .forms import Prop from django.shortcuts import get_object_or_404, render from scripts import load_data def index(request): template = loader.get_template('home.html') load_data.run() global p, i p = Mystere.objects.create(id=0) i = Image.objects.all().first() i = i.image p = Mystere.objects.all().last() p = p.individu rep=Prop() context = {'question': i, 'form': rep, } … -
Django viewflow custom permissions
Probably something simple. I am trying to follow the cookbook example on the following link https://github.com/viewflow/cookbook/tree/master/guardian. With the exception of a couple of unrelated differences between the example and my own code (I am not using frontend and am using custom views). Everything else works as expected. I do not understand what I am getting wrong on the permissions side of things. I am getting a "403 forbidden" error whenever a user other than the one that started the process tries to interact with the flow. This happens irrespective of the assigned user's assigned permissions - is this the expected behavior or should I open a ticket on Github? While I am trying to understand if viewflow can support what I am trying to accomplish - I would like to leave apply the permissions checking on my own views (rather than the built in checks). I saw that there was a pull request https://github.com/viewflow/viewflow/issues/252 - however, I do not understand how to implement it. Any help would be appreciated! Been stuck on this for quite a while The permissions are defined in a custom user class accounts/models.py class Department(models.Model): name = models.CharField(unique=True, max_length=250) description = models.TextField(blank=True) objects = managers.DepartmentManager() class … -
django search and pagination using ajax
I want to implement search functionality and pagination in my django project by using ajax call.Without ajax call it works fine.But I want to implement without page reload.So in the console am getting searched string(search is done by using username) like results:username. I want to display that matched records from the mysql database in the form of a table.There are total 6 fields. Here, after searching the username the result should be displayed under the search box as table entries.How to modify my script and views for getting results in the form of table entries?Here it do not need to load all records.The table records should be fetch after search. user_management.html <form method="get" action="/home" id="form_search"> <div class="input-group"> <input name="results" id="results" type="text" placeholder="search" class="form-control form-control-lg" /> <div class="input-group-append"> <button class="btn btn-dark btn-lg" id="q" >Search</button> </div> </div> </form> </div> </div> </div> <div class="card-body" > {% if word %} {% for words in word %} <table class="table table-bordered" style="width:85%;margin-right:auto;margin-left:auto;" id="example" > <thead class="table-success"> {% endfor %} <tr> <th scope="col">Id</th> <th scope="col">Username</th> <th scope="col">Name</th> <th scope="col">Admin</th> <th scope="col">User</th> <th scope="col">Status</th> <th scope="col"></th> <th scope="col"></th> </tr> </thead> {% for words in word %} <tbody> <tr> <th>{{words.id}}</th> <th>{{words.username}}</th> <th>{{words.first_name}}</th> <th>{{words.is_superuser}}</th> <th>{{words.is_staff}}</th> <th>{{words.is_active}}</th> <th><a href="/update_user/{{words.id}}" class="btn btn-success" … -
Django: Change the parent, when the child get dleted(unidirectional OneToOne)
First of all, I am sorry for my poor English. I want to change Photo 'labeled' field False when I delete LabeledPhoto object. #models.py class Photo(models.Model): image = models.ImageField(upload_to='shoes_data/%Y/%m/%d', name='image') created = models.DateTimeField(auto_now_add=True) labeled = models.BooleanField(default=False) class LabeledPhoto(models.Model): labeled_image = models.OneToOneField(Photo, on_delete=models.PROTECT, related_name='labeled_image') topcategory = models.CharField(max_length=64) subcategory = models.CharField(max_length=64) labeler = models.CharField(max_length=32) created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) I tried like this but, It didn't work # views.py class LabeledPhotoDelete(DeleteView): model = LabeledPhoto template_name = 'label/labeled_photo_delete.html' success_url = reverse_lazy('photo:labeled_list') def delete(self, request, *args, **kwargs): self.object = self.get_object() success_url = self.get_success_url() labeled = LabeledPhoto.objects.get(id=self.object.pk) labeled.labeled_image.labeled = False labeled.save() self.object.delete() return reverse(success_url) Thank you in advance for your help. -
What is problem with ALLOWED_HOSTS = ['*'] in django in production.?
If source code is hidden what is point of not using * wild card object in django. Why Not to use this in production.? -
How to inherit Input inner class in Python graphene mutation to another Input inner class in another mutation?
I am creating a simple GraphQL request app in the backend using Django with graphene-django package. Waht I need is to inherit the Input inner class in the create mutation to the Input class for the update mutation. Can I do this using any way, and if not can any one help me solving this kind of issue, and to know that I know how to solve it but I don't want to rewrite the same field in the create and in the update mutations for the same model or type. This is a sample of my code: import graphene from graphene import relay from BoD.models import Meeting from BoD.types.meeting import MeetingType class CreateMeeting(relay.ClientIDMutation): """Mutation to create a new meeting.""" class Input: created_by_id = graphene.Int(required=True) subject = graphene.String(required=True) location = graphene.String(required=True) date = graphene.DateTime(required=True, datetime_input=graphene.DateTime(required=True)) start_time = graphene.Time(required=True) end_time = graphene.Time(required=True) meeting = graphene.Field(MeetingType) @classmethod def mutate_and_get_payload(cls, root, info, **input): """Create a new meeting.""" meeting = Meeting.objects.create(**input) return CreateMeeting(meeting=meeting) class UpdateMeeting(CreateMeeting): """Mutation to update a meeting.""" class Input(CreateMeeting.Input): id = graphene.Int(required=True) class MeetingMutate: class Meta: abstract = True created_by_id = graphene.Int(required=True) subject = graphene.String(required=True) location = graphene.String(required=True) date = graphene.DateTime(required=True, datetime_input=graphene.DateTime(required=True)) start_time = graphene.Time(required=True) end_time = graphene.Time(required=True) class CreateMeeting(relay.ClientIDMutation): """Mutation … -
How to get value from foreign kye in DJANGO?
Hey I have 2 models in my models.py: username = models.CharField(max_length=250, verbose_name='username', null=True) refresh_token = models.CharField(max_length=300, verbose_name='refresh_token', null=True) id = models.CharField(max_length=150 ,primary_key=True) login = models.CharField(max_length=250, null=True) avatar = models.CharField(max_length=400, verbose_name='avatar') params = models.ForeignKey('Parametrs', on_delete=models.CASCADE) class Parametrs(models.Model): cost_skip = models.IntegerField(null=True) chat_bot = models.BooleanField(default=False) and in views.py im need to get cost_skip of user. That is TwitchUser => username => cost_skip im tried to find something in docs, but it doesnt help -
why does my API crash without error message when calling cuda?
I built a django API which calls in some routes python functions which use GPU and cuda. When I call these routes the API always crash without an error message. I was thinking it was caused by a lack of RAM so I increased the memory on my server but it still doesn't work. Because there is no error message, I added a lot of print in my code until finding the problem always happend when the python code use cuda. Here is the code which make crash the API : from training.tacotron2_model import Tacotron2 model = Tacotron2().cuda() I tried different things and this one worked perfectly : model = Tacotron2() But it doesn't use GPU so that's not what I want, It just demonstrates the problem is only with cuda. What is the most interesting is that if I run both lines (using cuda) in a python terminal it perfectly works. So why doesn't it work when it's called by my django API ? I can't understand and have this problem with many routes since few days I specify that I use a Nvidia Tesla T4 and that cuda is right installed. I can see it by running nvcc … -
How to modify the request before View Class is invoked?
I already have a ModelViewSet. class ConfigManager(ModelViewSet): queryset = Configuration.objects.all() serializer_class = ConfigSerializer http_method_names = ["post", "get", "patch", "delete"] def perform_create(self, serializer): if Configuration.objects.count(): raise BadRequest( message="Only 1 Configuration is allowed. Try updating it." ) obj = serializer.save() tenant_id = self.request.META.get("HTTP_X_TENANT_ID") cache_config(obj, tenant_id) def perform_update(self, serializer): obj = serializer.save() tenant_id = self.request.META.get("HTTP_X_TENANT_ID") cache_config(obj, tenant_id) def perform_destroy(self, instance): if Configuration.objects.count() <= 1: raise BadRequest(message="One configuration object must exist.") instance.delete() obj = Configuration.objects.all().first() tenant_id = self.request.META.get("HTTP_X_TENANT_ID") cache_config(obj, tenant_id) Now I am trying to create a wrapper for this ViewSet Class, Where I want to perform some modifications to the request before serving it. How can I do this? class ConfigManagerWrapper(ConfigManager): pass -
Access a view which is for logged in users in django testing
Im trying to create some tests for my django project. I had no problem creating the models tests but i get multiple errors when trying to do the views tests. Most of my views depend on a user to be logged in and I cant find the way to log in . Im using the deafult django built-in AUTH system. VIEW : @login_required def fields(request): if request.user.profile.user_package == "Livestock": raise PermissionDenied() field_list = Field.objects.filter(user = request.user) context = { "title": "Fields", "field_list" : field_list, } template = 'agriculture/fields.html' return render(request, template, context) TetCase: class TestViews(TestCase): @classmethod @factory.django.mute_signals(signals.pre_save, signals.post_save, signals.pre_delete, signals.post_delete) def setUpTestData(cls): # Create new user test_user = User.objects.create(username='test_user',password='1XISRUkwtuK') test_user.save() c = Client() profile = Profile.objects.get_or_create(user = test_user, user_package = 'hybrid') c.login(username = test_user.username, password = test_user.password) Field.objects.create(user=test_user,friendly_name='Arnissa') def test_logged_in_user(self): login = self.client.login(username='test_user', password='1XISRUkwtuK') response = self.client.get(reverse('agriculture:fields')) # Check our user is logged in self.assertEqual(str(response.context['user']), 'test_user') # Check that we got a response "success" self.assertEqual(response.status_code, 200) path:path('fields', views.fields, name='fields') and settings if they provide any help : LOGIN_REDIRECT_URL = 'dashboard:index' LOGOUT_REDIRECT_URL = 'login' LOGIN_URL = 'login' On my tests i get the error TypeError: 'NoneType' object is not subscriptable when im checking if user is logged in .If i try … -
Django allauth redirect to signup route for user that registered with password and login with social login
I used Django allauth for user authentication in my app. When a user registers with google account with email and manual password and then tries to login with google social login, Django allauth redirect user to accounts/social/signup/ route and asks user to enter email address and after entering email address, tells user that email address already exist! I read allauth documentation and configurations, but nothing works for me, here is my confirmation in settings.py: ACCOUNT_AUTHENTICATION_METHOD = ('username_email') ACCOUNT_EMAIL_REQUIRED = True ACCOUNT_UNIQUE_EMAIL = True ACCOUNT_USERNAME_REQUIRED = False ACCOUNT_EMAIL_VERIFICATION = "mandatory" ACCOUNT_DEFAULT_HTTP_PROTOCOL = 'https' #### SOCIALACCOUNT_AUTO_SIGNUP = True SOCIALACCOUNT_EMAIL_VERIFICATION = "none" SOCIALACCOUNT_EMAIL_REQUIRED = True Any suggestion appreciated. -
django: how to pass .is_valid() condition without filling all parameters
with class TestQuestionList in the post function, I do not need to create a new object, so I do not need some fields, but django requires me to fill in these fields class TestQuestionList(APIView): def __init__(self): self.questions = [1] def get(self, request): romms = TestQuestionBlok.objects.filter(id__in=self.questions) serializer = TestQuestionSerializers(romms, many=True) return Response(serializer.data) def post(self, request, format=None): serializer1 = TestQuestionSerializers(data=request.data) if serializer1.is_valid() : self.questions = serializer1.data['questions'] return Response(serializer1.data, status=status.HTTP_200_OK) return Response(serializer1.errors, status=status.HTTP_400_BAD_REQUEST) How can I bypass these requirements? -
django channels test AsyncConsumer.__call__() missing 1 required positional argument: 'send'
I am using the code below in real environment. When I tried to write the test code, the following error occurred. It also works fine in my local environment. I tried to write the test code looking at channels test, but the error below occurred. What's wrong? routing.py from django.urls import path from .consumers import ExchangeRateConsumer websocket_urlpatterns = [ path("ws/exchange_rate/<str:currency>/", ExchangeRateConsumer.as_asgi()), ] asgi.py application = ProtocolTypeRouter( { "http": django_asgi_app, "websocket": AllowedHostsOriginValidator( AuthMiddlewareStack(URLRouter(websocket_urlpatterns)) ), } ) tests.py class ChannelTest(TestCase): async def test_channel_connect(self): communicator = HttpCommunicator(ExchangeRateConsumer, "GET", "/exchange_rate/USD") response = await communicator.get_response() error TypeError: AsyncConsumer.call() missing 1 required positional argument: 'send' -
No module named django-admin C:\Program Files\Python39\python3.exe
I have 2 python installed in my system. 1 - python 3.7.x 2 - python 3.9.x I have these 2 versions because I simultaneously work on different Django versions on my laptop. NOTE: I have renamed python.exe to python3.exe for the version of 3.9.x and kept python.exe for 3.7.x as it is. To run my Django == 2.x.x project, I write python manage.py runserver To run my Django == 3.9.x project, I write python3 manage.py runserver But when I try to create a new project using python3 -m django-admin startproject my_project_name it gives me an error of No module name django-admin I don't know why it gives me this error. can anyone guide me? -
How to make reverse for temporary url?
I have source url domain.ex/dir/video.mp4 I have temporary url domain.ex/vlink/temp.mp4 which I need to "connect" to source domain.ex/dir/video.mp4 The same domain. I use nginx to serve source url location /dir/ { alias /media/videos/; } My current urls.py path('vlink/<str:temp>', views.vlink, name='vlink'), view.py def vlink(request, temp): # drop extension mp4 s = temp.split('.')[0] # I retrieve original file name vid = TmpUrl.objects.filter(tmp_url = s).values('orig').first() v = vid['orig'] the_url = '/dir/'+v+'.mp4' return redirect(the_url) template.html <video> <source src="/vlink/{{vid}}.mp4" type="video/mp4"> </video> I don't need simple redirect. I need to hide source url. What I need: when user click play, the browser shows tmp url and play vid without redirect to source. How to do this? -
How to move ListBox items to another ListBox in django using jQuery and insert, update into database?
How to move ListBox items to another ListBox in django using jQuery and insert, update into database? -
ValueError: The view selection.views.register didn't return an HttpResponse object. It returned None instead
I currently work with student management system by using django. in that I found some errors. Anybody can help me. view.py def register(request): try: if request.method == 'POST': form = UserForm(request.POST) if form.is_valid(): new_user = form.save(commit=False) new_user.save() Student.objects.create(user=new_user) cd = form.cleaned_data user = authenticate(request,username=cd['username'],password=cd['password1']) if user is not None: if user.is_active: login(request, user) return redirect('login/edit/') else: return HttpResponse('Disabled account') else: return HttpResponse('Invalid Login') else: form = UserForm() args = {'form': form} return render(request, 'reg_form.html', args) except Exception as e: raise e forms.py class UserForm(UserCreationForm): class Meta: model = User fields = ['username', 'password1', 'password2'] help_texts = { 'username': 'same as your roll no.', } The code doesn't have any errors. It works fine. After filling the form, I click register button. It will functioning and post request also done but returning null value. Anybody can fix this.