Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django migration problem with long traceback
I have a strange and frustrating problem with migration that I can't figure out. I'm not experienced in debugging. The steps before python3 manage.py makemigrations was OK. This is the log I kept. Could you please help me? ruszakmiklos@Ruszak-MacBook-Pro firm % python3 manage.py migrate Operations to perform: Apply all migrations: admin, auth, contenttypes, sessions, stressz Running migrations: Applying stressz.0050_auto_20210504_0757...Traceback (most recent call last): File "/Library/Python/3.8/site-packages/django/db/models/fields/__init__.py", line 1774, in get_prep_value return int(value) ValueError: invalid literal for int() with base 10: '' The above exception was the direct cause of the following exception: Traceback (most recent call last): File "manage.py", line 22, in <module> main() File "manage.py", line 18, in main execute_from_command_line(sys.argv) File "/Library/Python/3.8/site-packages/django/core/management/__init__.py", line 401, in execute_from_command_line utility.execute() File "/Library/Python/3.8/site-packages/django/core/management/__init__.py", line 395, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/Library/Python/3.8/site-packages/django/core/management/base.py", line 330, in run_from_argv self.execute(*args, **cmd_options) File "/Library/Python/3.8/site-packages/django/core/management/base.py", line 371, in execute output = self.handle(*args, **options) File "/Library/Python/3.8/site-packages/django/core/management/base.py", line 85, in wrapped res = handle_func(*args, **kwargs) File "/Library/Python/3.8/site-packages/django/core/management/commands/migrate.py", line 243, in handle post_migrate_state = executor.migrate( File "/Library/Python/3.8/site-packages/django/db/migrations/executor.py", line 117, in migrate state = self._migrate_all_forwards(state, plan, full_plan, fake=fake, fake_initial=fake_initial) File "/Library/Python/3.8/site-packages/django/db/migrations/executor.py", line 147, in _migrate_all_forwards state = self.apply_migration(state, migration, fake=fake, fake_initial=fake_initial) File "/Library/Python/3.8/site-packages/django/db/migrations/executor.py", line 227, in apply_migration state = migration.apply(state, schema_editor) File "/Library/Python/3.8/site-packages/django/db/migrations/migration.py", line 124, … -
please solve this DLL load failed
Process Process-1: Traceback (most recent call last): File "C:\DeepFaceLab_NVIDIA_up_to_RTX2080Ti_internal\python-3.6.8\lib\site-packages\tensorflow\python\pywrap_tensorflow.py", line 58, in from tensorflow.python.pywrap_tensorflow_internal import * File "C:\DeepFaceLab_NVIDIA_up_to_RTX2080Ti_internal\python-3.6.8\lib\site-packages\tensorflow\python\pywrap_tensorflow_internal.py", line 28, in _pywrap_tensorflow_internal = swig_import_helper() File "C:\DeepFaceLab_NVIDIA_up_to_RTX2080Ti_internal\python-3.6.8\lib\site-packages\tensorflow\python\pywrap_tensorflow_internal.py", line 24, in swig_import_helper _mod = imp.load_module('_pywrap_tensorflow_internal', fp, pathname, description) File "imp.py", line 243, in load_module File "imp.py", line 343, in load_dynamic ImportError: DLL load failed: The specified module could not be found. During handling of the above exception, another exception occurred: Traceback (most recent call last): File "multiprocessing\process.py", line 258, in bootstrap File "multiprocessing\process.py", line 93, in run File "C:\DeepFaceLab_NVIDIA_up_to_RTX2080Ti_internal\DeepFaceLab\core\leras\device.py", line 101, in get_tf_devices_proc import tensorflow File "C:\DeepFaceLab_NVIDIA_up_to_RTX2080Ti_internal\python-3.6.8\lib\site-packages\tensorflow_init.py", line 24, in from tensorflow.python import pywrap_tensorflow # pylint: disable=unused-import File "C:\DeepFaceLab_NVIDIA_up_to_RTX2080Ti_internal\python-3.6.8\lib\site-packages\tensorflow\python_init.py", line 49, in from tensorflow.python import pywrap_tensorflow File "C:\DeepFaceLab_NVIDIA_up_to_RTX2080Ti_internal\python-3.6.8\lib\site-packages\tensorflow\python\pywrap_tensorflow.py", line 74, in raise ImportError(msg) ImportError: Traceback (most recent call last): File "C:\DeepFaceLab_NVIDIA_up_to_RTX2080Ti_internal\python-3.6.8\lib\site-packages\tensorflow\python\pywrap_tensorflow.py", line 58, in from tensorflow.python.pywrap_tensorflow_internal import * File "C:\DeepFaceLab_NVIDIA_up_to_RTX2080Ti_internal\python-3.6.8\lib\site-packages\tensorflow\python\pywrap_tensorflow_internal.py", line 28, in _pywrap_tensorflow_internal = swig_import_helper() File "C:\DeepFaceLab_NVIDIA_up_to_RTX2080Ti_internal\python-3.6.8\lib\site-packages\tensorflow\python\pywrap_tensorflow_internal.py", line 24, in swig_import_helper _mod = imp.load_module('_pywrap_tensorflow_internal', fp, pathname, description) File "imp.py", line 243, in load_module File "imp.py", line 343, in load_dynamic ImportError: DLL load failed: The specified module could not be found. Failed to load the native TensorFlow runtime. See https://www.tensorflow.org/install/errors for some common reasons and solutions. Include the entire stack trace above … -
Django: AttributeError: 'int' object has no attribute 'cafe_name'
Hey I am trying to return a set of objects that belong to "friends" the logged in user follows and are within a specific geographic space. But I get this error: AttributeError: 'int' object has no attribute 'cafe_name' views.py def get_friends(request): template_name = 'testingland/electra.html' neLat = request.GET.get('neLat', None) neLng = request.GET.get('neLng', None) swLat = request.GET.get('swLat', None) swLng = request.GET.get('swLng', None) ne = (neLat, neLng) sw = (swLat, swLng) xmin = float(sw[1]) ymin = float(sw[0]) xmax = float(ne[1]) ymax = float(ne[0]) bbox = (xmin, ymin, xmax, ymax) geom = Polygon.from_bbox(bbox) friends = UserConnections.objects.filter( follower=request.user ).values_list('followed__pk', flat=True) mapCafes.objects.filter( geolocation__coveredby=geom, uservenue__user_list__user__pk__in=friends ).distinct() return JsonResponse([ [cafe.cafe_name, cafe.cafe_address, cafe.geolocation.y, cafe.geolocation.x] for cafe in friends ], safe=False) Models class mapCafes(models.Model): id = models.BigAutoField(primary_key=True) cafe_name = models.CharField(max_length=200) cafe_address = models.CharField(max_length=200) cafe_long = models.FloatField() cafe_lat = models.FloatField() geolocation = models.PointField(geography=True, blank=True, null=True) venue_type = models.CharField(max_length=200) source = models.CharField(max_length=200) description = models.CharField(max_length=1000) image_embed = models.CharField(max_length=10000) class Meta: managed = False db_table = 'a_cafes' def __str__(self): return self.cafe_name [...] class UserConnections(models.Model): follower = models.ForeignKey(User, related_name="following", on_delete=models.CASCADE) followed = models.ForeignKey(User, related_name="followers", on_delete=models.CASCADE) Traceback: Internal Server Error: /electra/get_friends/ Traceback (most recent call last): File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/django/core/handlers/exception.py", line 47, in inner response = get_response(request) File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/django/core/handlers/base.py", line 181, in _get_response response = wrapped_callback(request, *callback_args, … -
SSO with roles and permissions
We have projects that interacts with regular users (general app) and company users (companies app). Therefore, in our projects, generally, we have two types of Users: Regular - authenticates with phone_number as identifier. Regular users are any Users that can do common staff in our system. Staff - authenticates with email as identifier. Staff Users belong to some company and they have some roles. So, we built SSO app, that keeps all users, because there are apps that need about any user and having separate app that handles users in one place was for us better choice. However, there are troubles with our idea... The company app has its SUPERUSER that can create some company, company branch and director of that company and etc. We create company-apps superuser in our SSO app and give it COMPANY APP SUPERUSER role. SSO app does not hold the specific roles of company for users, we don't want it. That is the responsibility of company app. So, there is the problem when director of company wants to invite (create) employee, he/she requests company-app, which in the box calls SSO app endpoint to create user. Inside of SSO app we don't know who is requesting … -
showing same output for different list views
i am making a html page which shows list of companies follow by its product. i used 2 models(company, product) for 1st html and it worked but when i tried creating the same 2 models for different type it shows the output of 1st model my models.py: class HydraulicCompany(models.Model): name = models.CharField(max_length=200) def __str__(self): return self.name class HydraulicProduct(models.Model): company = models.ForeignKey(HydraulicCompany, on_delete=models.CASCADE, related_name='company') name = models.CharField(max_length=200) def __str__(self): return self.name class Industrial_Company(models.Model): name = models.CharField(max_length=200) def __str__(self): return self.name class Industrial_Product(models.Model): company = models.ForeignKey(Industrial_Company, on_delete=models.CASCADE, related_name='ind_company') name = models.CharField(max_length=200) def __str__(self): return self.name my views.py: class Hydraulic(ListView): template_name = 'hydraulics.HTML' context_object_name = 'hydraulic' queryset = models.HydraulicProduct.objects.select_related('company').order_by('company') class igo(ListView): model = Industrial_Product template_name = 'industialgear.html' context_object_name = 'igo' queryset = models.HydraulicProduct.objects.select_related('company').order_by('company') my html: {% extends "base.HTML" %} {% load static %} {% block title %}industrial gear oil{% endblock %} {% block extra_head %} <link rel="stylesheet" href="{% static 'css/data.css' %}"> {% endblock %} {% block content %} <br><br><br><br><br><br> {% for item in igo %} {% ifchanged item.company %} <h1> {{ item.company }} </h1> {% endifchanged %} <div> {{ item }} </div> {% endfor %} {% endblock %} THANKS! -
How to Sum same product's product _Volume value at with ORM-Query
I need to sum all different product's "product_volume" in one for this my model is class Product(BaseModel, models.Model): name = models.CharField(max_length=256) category = models.ForeignKey(Category, null=True, blank=True, on_delete=models.SET_NULL, related_name='product_category') description = models.CharField(max_length=1000) hs_code = models.CharField(max_length=256, unique=True) photo = models.ImageField(upload_to='media/product/%Y/%M/', null=True, blank=True) production_unit = models.ForeignKey(MeasurementUnit, related_name='product_unit', null=True, blank=True, on_delete=models.SET_NULL) class Production(BaseModel, models.Model): product = models.ForeignKey(Product, related_name='production_product', on_delete=models.CASCADE) district = models.ForeignKey(DistrictLevel, related_name='production_district', on_delete=models.CASCADE) production_volume = models.FloatField() production_year = models.ForeignKey(FiscalYear, related_name='production_year', null=True, blank=True, on_delete=models.SET_NULL) seasons = models.ManyToManyField(Season) Here, I'm trying to do is that, sum of the product_volume of product at one like, product1, product_volume=20 product2, product_volume = 40 product3, product_volume = 60 in my table i need to show product1, product_volume = 80 product2, product_volume = 40 Here is my table I'm getting result by using for loop but, is there any better solution for this using ORM. sorry for my English, I'm little weak in English -
Using Django Session ID from cookies to authenticate Vue app
I'm trying to use the session id generated when logging in a users on a Django site, to then automatically login a user on a Vue site. Both the Vue site and Django site run on different servers, but Vue uses the Django site as an api. Is this safe and recommended and how can this be achieved? Would if be safer to use the session id and then generate a token for the vue site? -
How to pass model instance to serializer?
I have a view: def create(self, request): serializer = OrderPostSerializer(data=request.data) if serializer.is_valid(): instance = serializer.save() serializer = OrderDetailsSerializer(instance) return AppResponse.success( "Order created successfully.", serializer.data, http_success_code=status.HTTP_201_CREATED, ) return AppResponse.error( serializer.errors, None, http_error_code=status.HTTP_422_UNPROCESSABLE_ENTITY, ) Serializers: class CustomerDetailsPostSerializer(serializers.Serializer): id = serializers.IntegerField( required=False, error_messages={"invalid": "id should be a valid integer."} ) name = serializers.CharField(required=False, max_length=80) email = serializers.EmailField(required=False) mobile = serializers.CharField( required=False, max_length=15, error_messages={ "max_length": "mobile field should not exceed more than 15 characters." }, ) company_name = serializers.CharField( required=False, max_length=255, allow_null=True, error_messages={ "max_length": "company name field should not exceed more than 255 characters." }, ) def validate_email(self, value): customer = Customer.objects if self.instance: customer = customer.exclude(pk=self.instance.pk) if customer.filter(email__iexact=value): raise serializers.ValidationError( "Customer with this email already exists." ) return value def validate_company(self, value): customer = Customer.objects if self.instance: customer = customer.exclude(pk=self.instance.pk) if customer.filter(company_name__iexact=value): raise serializers.ValidationError( "Customer with this company name already exists." ) return value def validate_mobile(self, value): if validate_phone_number(value) is None: customer = Customer.objects if self.instance: customer = customer.exclude(pk=self.instance.pk) if customer.filter(mobile__iexact=value): raise serializers.ValidationError( "Customer with this phone number already exists." ) return value def validate(self, data): data = dict(data) if ("id" not in data.keys() or not data.get("id")) and ( ("name" not in data.keys() or not data.get("name")) or ("email" not in data.keys() or not … -
CustomUser matching query does not exist. ERROR( DJANGO)
when i save the form in template. The error says: CustomUser matching query does not exist. Line number 104: teacher=CustomUser.objects.get(id=teachers_id) Model.py class Subjects(models.Model): id=models.AutoField(primary_key=True) subject_name=models.CharField(max_length=255) course_id=models.ForeignKey(Courses,on_delete=models.CASCADE,default=1) teachers_id=models.ForeignKey(CustomUser,on_delete=models.CASCADE) created_at=models.DateTimeField(auto_now_add=True) updated_at=models.DateTimeField(auto_now_add=True) objects=models.Manager() views.py def add_subject_save(request): if request.method!="POST": return HttpResponse("<h2>Method Not Allowed</h2>") else: subject_name=request.POST.get("subject_name") course_id=request.POST.get("course") course=Courses.objects.get(id=course_id) teachers_id=request.POST.get("teacher") teacher=CustomUser.objects.get(id=teachers_id) try: subject=Subjects(subject_name=subject_name,course_id=course,teachers_id=teacher) subject.save() messages.success(request,"Successfully Added Subject") return HttpResponseRedirect("add_subject") except: messages.error(request,"Failed to Add Subject") return HttpResponseRedirec("add_subject") I dont know where this error is coming from. -
Failed to send email using gmail as client (django, graphene)
I am trying to set up email client to be gmail in my django project. When i register a user it gives me the following error: { "data": { "register": { "success": false, "errors": { "nonFieldErrors": [ { "message": "Failed to send email.", "code": "email_fail" } ] }, "token": null } } } My settings.py looks like this EMAIL_BACKEND = "django.core.mail.backends.smtp.EmailBackend" EMAIL_HOST = "smtp.gmail.com" EMAIL_PORT = 587 EMAIL_USE_TLS = True EMAIL_HOST_USER = "youremail@gmail.com" EMAIL_HOST_PASSWORD = "yourpassword" I have already enabled 2 step authentication with google. My AuthMutation looks like this: class AuthMutation(graphene.ObjectType): register = mutations.Register.Field() verify_account = mutations.VerifyAccount.Field() login = mutations.ObtainJSONWebToken.Field() update_account = mutations.UpdateAccount.Field() resend_activation_email = mutations.ResendActivationEmail.Field() send_password_reset_email = mutations.SendPasswordResetEmail.Field() password_reset = mutations.PasswordReset.Field() password_change = mutations.PasswordChange.Field() Thanks in advance to the amazing stackoverflow community -
TypeError at /myaccount/ myaccount() missing 1 required positional argument: 'id'
I am looking to update the profile of my user in Django. However, I am getting a strange errorTypeError at /myaccount/ myaccount() missing 1 required positional argument: 'id' as Error when I open the webpage. Below, are my models.py, views.py, urls.py and forms.py files containing details of the same. How can I fix this issue. models.py: class User_profile(models.Model): user = models.OneToOneField(User,on_delete=models.CASCADE,related_name="userprofile") Address = models.CharField(max_length=150) Skills = models.CharField(max_length=150) Work_Experiences = models.CharField(max_length = 150) Marital_Status = models.CharField(max_length = 150) Interests = models.CharField(max_length = 150) Edcucation = models.CharField(max_length = 150) category = models.ForeignKey("Category.Category",on_delete=models.CASCADE,default="demo") sub_category = models.ForeignKey("Category.SubCategory",on_delete=models.CASCADE,default="demo") phone_number = models.CharField(max_length=11) Aadhar_Card = models.FileField(upload_to="user_aadhar_card/",default="") def __str__(self): return str(self.user) forms.py: class UserForm(forms.ModelForm): class Meta: model = User fields = ["username", "email", "password","first_name","last_name"] class UserProfileForm(forms.ModelForm): class Meta: model = User_profile fields = '__all__' exclude = ['user'] def _init_(self, *args, **kwargs): super()._init_(*args, **kwargs) self.fields['first_name'].widget.attrs.update({'id':'fname','class': 'form-control'}) self.fields['last_name'].widget.attrs.update({'id':'lname','class': 'form-control'}) self.fields['email'].widget.attrs.update({'id':'email','class': 'form-control'}) self.fields['username'].widget.attrs.update({'id':'uname','class': 'form-control'}) self.fields['password'].widget.attrs.update({'id':'password','class': 'form-control'}) self.fields['Address'].widget.attrs.update({'id':'address','class': 'form-control'}) self.fields['Skills'].widget.attrs.update({'id':'skills','class': 'form-control'}) self.fields['Work_Experiences'].widget.attrs.update({'id':'we','class': 'form-control'}) self.fields['Marital_Status'].widget.attrs.update({'id':'ms','class': 'form-control'}) self.fields['Interests'].widget.attrs.update({'id':'inte','class': 'form-control'}) self.fields['Edcucation'].widget.attrs.update({'id':'edu','class': 'form-control'}) self.fields['category'].widget.attrs.update({'id':'category','class': 'form-control'}) self.fields['sub_category'].widget.attrs.update({'id':'subcategory','class': 'form-control'}) self.fields['phone_number'].widget.attrs.update({'id':'phonenumber','class': 'form-control'}) self.fields['Aadhar_Card'].widget.attrs.update({'id':'aadhar','class': 'form-control'}) views.py: def myaccount(request,id): instance1 = User_profile.objects.get(id=id) if request.method == "POST": user_form = UserForm(request.POST,instance=request.user) profile_form = UserProfileForm(request.POST,instance1=instance1) if user_form.is_valid(): user_form.save() messages.success(request,('Your profile was successfully updated!')) elif profile_form.is_valid(): profile_form.save() messages.success(request,('Your profile was successfully updated!')) else: messages.error(request,('Unable to … -
How to overwrite data from a model that is linked to the main model through a o-t-m relationship?
I have three models that are related to each other, namely: models.py class Shop(models.Model): number = models.PositiveSmallIntegerField() name = models.CharField(db_index=True) city = models.ForeignKey(ShopCity, on_delete=models.CASCADE) class Product(models.Model): name = models.CharField(db_index=True) price = models.DecimalField(max_digits=10, decimal_places=2) class ProductQuantity(models.Model): product = models.ForeignKey(Product, on_delete=models.CASCADE) shop = models.ForeignKey(Shop, on_delete=models.CASCADE) quantity = models.PositiveSmallIntegerField(default=None) In the admin panel they are linked in this way: admin.py class ProductQuantityInline(admin.TabularInline): model = ProductQuantity extra = 0 @admin.register(Product) class ProductAdmin(ImportExportActionModelAdmin): fields = ['name', 'price'] list_display = ['name', 'price'] inlines = [ProductQuantityInline] There is a need to overwrite data with REST API serializers.py class QuantitySerializer(serializers.ModelSerializer): class Meta: model = ProductQuantity fields = ('shop', 'quantity') class ProductSerializer(serializers.ModelSerializer): productquantity = serializers.SerializerMethodField(read_only=False) class Meta: model = Product fields = ('name', 'price', 'productquantity') def get_productquantity(self, obj): return [QuantitySerializer(s).data for s in obj.productquantity_set.all()] And finally my handler for REST API: views.py @api_view(['GET', 'PATCH', 'PUT', 'DELETE']) def api_product_detail(request, pk): product = Product.objects.get(pk=pk) if request.method == 'GET': serializer = ProductSerializer(product) return Response(serializer.data) elif request.method == 'PUT' or request.method == 'PATCH': serializer = ProductSerializer(product, data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) elif request.method == 'DELETE': product.delete() return Response(status=status.HTTP_204_NO_CONTENT) As a result, data such as the name and price are overwritten, and the productquantity is not overwritten. What am I … -
How is front end generated when creating web applications using python Django? [closed]
First off, bare with me if my question seems odd as i have no experience in developing web applications. I know Django is used for the backend and the logic of a web application i.e website. But how is the front end and HTML, CSS, JS and all those UI stuff created when working with Django? Does the programmer separately write the UI with those mark up languages or does the Django framework create web pages automatically? -
how to display data from json response django
i want to add a function to my project to return json data and display it in the main template (base.html) using ajax , this is my function @login_required def alerts(request): if request.is_ajax: sender = Post.objects.filter(active=False) return JsonResponse(sender) my models.py class Post(models.Model): title = models.CharField(max_length=50) active = models.BooleanField(default=True) #others and this is my base.html $(document).ready(function(){ $('.btn-click').click(function(){ $.ajax({ url:'/ajax/alerts/', type:'get', success:function(data){ document.getElementById('alerts').append(data.title) } }) }) }) <div x-data="{ dropdownOpen: false }"> <button @click="dropdownOpen = !dropdownOpen" class="relative z-10 block rounded-md text-black p-2 focus:outline-none btn-click"> <i class="fas fa-bell"></i> <!-- <img src="icon/bell.svg" class="w-5" alt=""> --> </button> <div x-show="dropdownOpen" class="absolute left-2 top-10 text-right py-2 w-59 grayBG rounded-md shadow-xl z-20 h-48 overflow-y-scroll "> <p class="whiteCOLOR text-center border-b border-red-500 p-2" id="alerts"></p> </div> </div> and my urls.py path('ajax/alerts', alerts,name='alerts'), but it shows nothing !? i want to display those posts which not accepted in an alert , thank you .. -
Use global variable in Django instead of session variable?
I have a Django project that uses a pretty complex object which I would like to pass around in views. Now, normally one would use the session variables for that: request.session['variable'] = complex_object I am aware that this is the normal way to do this. Alas, my very complex object is not JSON serializable so I cannot save it as a session variable. One way to solve this would be to write a serializer for the object. But since the object is really horribly complex and nested, this is not even tedious: it's impossible. So I was searching for an easier workaround. I started working with global variables. This is bad practice, I know, but I need a solution. Global variables work very well in development. But as soon as I deploy the project, they start becoming very unreliable. Sometimes they work, sometimes they don't. So this can't be the way either. To not make this question too text heavy, some pseudo code to show you my global variables in principle: global p def a(request): global p p = 5 def b(request): global p print(p) As I said, doing this in development works well. In production, not so much. Any … -
how to use `commit=False` in django views for getting foreign key values?
views fun:- def save_all_form_at_once(request): if request.method == 'POST': form1 = StudentForm( request.POST, prefix="form1") form2 = GradeForm( request.POST, prefix="form2") form3 = SemesterForm( request.POST, prefix="form3") form4 = CourseForm( request.POST, prefix="form4") if all([form1.is_valid() , form2.is_valid() , form3.is_valid() , form4.is_valid()]): form1.save() dont know how to get following values # new_course = form4.save(commit=False) # new_course.student_id = form1.get("enroll_no") # new_course.save() # new_sem = form3.save(commit=False) # new_sem.student_id = form1.get("enroll_no") # new_sem.course_id = new_course.get("id") # new_sem.save() # new_grade = form2.save(commit=False) # new_grade.Sem_Info_id = new_sem.get("id") # new_grade.Student_Name_id = form1.get("enroll_no") # new_grade.Subject_Info_id = new_course.get("id") # new_grade.save() else: form1 = StudentForm(prefix="form1") form2 = GradeForm(prefix="form2") form3 = SemesterForm(prefix="form3") form4 = CourseForm(prefix="form4") return render(request, 'add.html', {'form1' : form1, 'form2' : form2, 'form3' : form3, 'form4' : form4 } ) models.py file as you can see I didn't put null=Flase in any of FK because I need them in my DB. how can I get all those FK values and save into my DB I need all FK values. and have no idea how to do it! if I'm doing in the wrong way please correct me! -
Django FileNotFoundError: [WinError 3] The system cannot find the path specified: 'C:\\Users\\ivan\\Desktop\\Python\\static'
I'm trying to install django debug toolbar to track ORM queries to the database. Can't use python manage.py collectstatic and getting the error Here's the settings files settings.py INSTALLED_APPS = [ #... 'django.contrib.staticfiles', #.. 'debug_toolbar', ] MIDDLEWARE = [ #... 'debug_toolbar.middleware.DebugToolbarMiddleware', ] # ... DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': str(os.path.join(BASE_DIR, "db.sqlite3")), } } # .... STATIC_URL='/static/' STATICFILES_DIRS =[ os.path.join(BASE_DIR,'static').replace("\\", "/"), ] -
Django-reversion foreign-key data "follow" question - get related model instance from history when object was created
Say I have models: @reversion.register() class EmailTemplate(models.Model): html_content = models.TextField() context_variables = models.JSONField() @reversion.register(follow="template") class EmailMessage(models.Model): template = models.ForeignKey(EmailTemplate) custom_data = models.JSONField() Case 1: EmailTemplate data: html_content = """ Hello {{ first_name }} """ context_variables = {'first_name': 'Enter name' } EmailMessage data: template = ForeignKey(EmailTemplate with id: 1)) custom_data = {'first_name': 'Robert } I parse this to make additional form fields when creating new email message from template. It lets me declare fields for this email template and form within the EmailTemplate. I create EmailTemplate in admin, so I can see all history versions. The problem is when I select an email from my sent emails list to send again the email with this specified template version (it may be from the past) as the template could be modified later. I know I can create a new template, but there will be many and I won't bother you with the reasons behind my desicion of using reversion. I would also like to avoid attaching large html content to my EmailMessage instance saved to the db. There will be more functionalities like view the web version of this email, unsubscribe etc. I'd rather just be able to render the template (via … -
Django deserialize with one field but serialize with other field
I have two models. Bar is related to Foo via foreign key. In my Bar serializer, I have FooSerializer so it can serializer from its model: class BarSerializer(serializers.ModelSerializer): foo = FooSerializer(source='*') ... class Meta: model = Bar then my Foo Serializer looks like: class FooSerializer(serializers.ModelSerializer): name = serializers.StringRelatedField() link = serializers.SerializerMethodField() class Meta: model = Foo fields = ('name', 'link') def to_internal_value(self, data): # Save depending on name foo = Foo.objects.get(name=data) return {'foo': foo} def get_link(self, object): print('req', object.id) if object.id and request: return request.build_absolute_uri( '/app/foo/{}'.format(object.id)) return None I want to able to post in Bar with Foo's name field, for example: { "bar_name": "Nikko", "foo": "The Foo", } but the response I want is: { "bar_name": "Nikko", "foo": { "name": "The Foo", "link": "https://localhost:8000/apps/foo/1", } } -
How two diffrent docker container api communicate with each other requests?
In one container there Django app running which expose to host port 8000 and another container flask app is running which expose to the host port 8001. So there is a condition where the flask app API end needs to communicate with the Django app API end. Code req = requests.get('http://192.168.43.66:8000/api/some') Error requests.exceptions.ConnectionError: HTTPConnectionPool(host='192.168.43.66', port=8000): Max retries exceeded with url: /api/user (Caused by NewConnectionError('<urllib3.connection.HTTPConnection object at 0x7fc6f96942e0>: Failed to establish a new connection: [Errno 110] Connection timed out')) But if I change the request URL to some other API end which not running on the container it gets the response. And each Django API end is working fine if I want to access it through some other external source like postman or browser. -
NameError: name 'DeliveryOrder' is not defined
Here I am trying to call deliveryorder as ForeignKey into the PurchaseOrder table. Once I run makemigrations it shows the above error. Moreover, I can not write the PurchaseOrder definition after the DeliveryOrder because the DeliveryOrder table also holding PurchaseOrder as ForeignKey. Purchase Order class PurchaseOrder(models.Model): part = models.ForeignKey(Part, on_delete=models.CASCADE) deliveryorder = models.ForeignKey(DeliveryOrder) po_quantity = models.PositiveIntegerField(default= 0) supplier = models.ForeignKey(Supplier, on_delete=models.CASCADE) product = models.ForeignKey(Product, on_delete=models.CASCADE) created_date = models.DateField(auto_now_add=True) def __str__(self): return self.part.partname Delivery Order class DeliveryOrder(models.Model): purchaseorder = models.ForeignKey(PurchaseOrder, on_delete=models.CASCADE) do_quantity = models.PositiveIntegerField(default= 0) created_date = models.DateField(auto_now_add=True) def __str__(self): return self.do_quantity Can suggest to me how to overcome this issue? -
How to stream IOT signals from Celery/Django?
I have an IoT device that generates 10 datapoints/sec (16 numbers in one datapoint). I want to stream that data into a web app and display it as a real-time graph. I'm using Django as backend, Celery/Redis for background tasks, and Channels for socket connections. Celery task @shared_task def start_eeg_stream(room_group_name, room_name): channel_layer = get_channel_layer() redis_uri = config('REDIS_URL') host, password = redis_uri.split('@')[1].split(':')[0], redis_uri.split('@')[0].split(':')[2] r = redis.Redis(host=host, password=password) pub_sub = r.pubsub() pub_sub.subscribe(f'EEG:{room_name}') r.set(room_name, 1) for message in pub_sub.listen(): if message and message['type'] == 'message': # do something with the message async_to_sync(channel_layer.group_send)( room_group_name, { 'type': 'socket_message', 'payload': {"type": "EEG_POINT", "value": str(message['data'])} } ) if not int(r.get(room_name)): print('stopping eeg stream..') break Django consumers.py import json from asgiref.sync import async_to_sync from channels.generic.websocket import WebsocketConsumer from .tasks import start_eeg_stream, stop_eeg_stream class LiveDataConsumer(WebsocketConsumer): def __init__(self) -> None: super().__init__() self.consumer = None def connect(self): self.room_name = self.scope['url_route']['kwargs']['room_name'] self.room_group_name = 'GROUP_%s' % self.room_name # Join room group async_to_sync(self.channel_layer.group_add)( self.room_group_name, self.channel_name ) self.accept() self.send(text_data=json.dumps({'value': 'Connected', 'type': "CONN_SUCCESS"})) def disconnect(self, close_code): # Leave room group stop_eeg_stream(self.room_name) async_to_sync(self.channel_layer.group_discard)( self.room_group_name, self.channel_name ) # Receive message from WebSocket def receive(self, text_data): data_json = json.loads(text_data) # Send message to room group async_to_sync(self.channel_layer.group_send)( self.room_group_name, { 'type': 'socket_message', 'payload': data_json } ) # Receive message from room … -
How to make many to one field in Django?
I want to make simple Django project based on book - author - publication Here book has an author but author has multiple books. Second I want relationship between book and publications, like publication has multiple books but book has one publication (if book published) or book has no publication (if book is not published) how can I make model for it ? Where to use foreign key in this? -
Shared library between multiple Django projects?
If I have 2 Django apps, how could I share a common library between both? I was thinking about a third library project, that I shortcut to in the other 2 projects locally, & on production replace the shortcut with the whole Library folder. would something like this work? and if so, how would I switch out the shortcut for the actual folder on release? -
How can I schedule a task in my djnago amazon product tracking project?
I am working on a web-app project with Django. It is an Amazon product price tracker. I want the app to automatically scrape products in the product table to check if the price of the product has reduced or not. I want to deploy the application once it is finished so it should work there too. I looked for answered online but it seems that cronjobs and celery do not work for windows so is there any other ways I can achieve my goals. I have created a function that needs to be executed once every day. This is the function I want to execute every 24 hours. def track(): products = Product.objects.all() for product in products: new_data = getproduct(product.link) update_data(product, new_data) I have tried the schedule library: import schedule import time from .models import Product from .utils import getproduct schedule.every().day.at("12:00").do(track) here getproduct is the method which scrapes the product data and product is the model