Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Link two models
I have two models: Profile and Course. Profile stores user info. Course has a title, description and date. User can sign up for the course using link. My goal is to make a list of users, who belong to each course. I tried using ForeignKey, but i need to have user added to the list only after he signs up for it. class Course(models.Model): course_title = models.CharField(max_length=200) course_description = models.TextField() course_published = models.DateTimeField("date published", default = datetime.now()) course_users = [] def __str__(self): return self.course_title def course_signup(request): # here i guess i need to somehow add the user to the list Course.course_users.append(Profile.id) return redirect("main:homepage") Profile code: class Profile (models.Model): user=models.OneToOneField(User, on_delete=models.CASCADE) image=models.ImageField(default='default.jpg',upload_to='profile_pics') def __str__(self): return f'{self.user.username} Profile' def save(self, *args, **kwargs): super(Profile,self).save(*args,**kwargs) img = Image.open(self.image.path) if img.height > 300 or img.width >300: output_size = (300,300) img.thumbnail(output_size) img.save(self.image.path) I expect to have a list of users in Course. -
Why is my auto-generated migration producing an error when I run it?
I'm using Python 3.7, Django, and PostGres 9.5. I recently edited my model to remove some columns and add another ... class MainSiteStatByHour(models.Model): total_score = models.DecimalField(default=0, max_digits=12, decimal_places=2) num_articles = models.IntegerField(default=0) hour_of_day = IntegerField( null=True, validators=[ MaxValueValidator(23), MinValueValidator(0) ] ) index = models.FloatField(default=0) ... class Meta: unique_together = ("hour_of_day",) I generated my migration and all seemed to go well ... (venv) localhost:mainsite_project davea$ python manage.py makemigrations mainsite Did you rename mainsitestatbyhour.elapsed_time_in_seconds to mainsitestatbyhour.index (a FloatField)? [y/N] N Migrations for 'mainsite': mainsite/migrations/0019_auto_20190401_2139.py - Add field index to mainsitestatbyhour - Remove field elapsed_time_in_seconds from mainsitestatbyhour - Remove field website from mainsitestatbyhour - Alter unique_together for mainsitestatbyhour (1 constraint(s)) The migration looks like this: # Generated by Django 2.1.4 on 2019-04-01 21:39 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('mainsite', '0018_auto_20190401_1713'), ] operations = [ migrations.AddField( model_name='mainsitestatbyhour', name='index', field=models.FloatField(default=0), ), migrations.RemoveField( model_name='mainsitestatbyhour', name='elapsed_time_in_seconds', ), migrations.RemoveField( model_name='mainsitestatbyhour', name='website', ), migrations.AlterUniqueTogether( name='mainsitestatbyhour', unique_together={('hour_of_day',)}, ), ] But when I go to run the migration, I get an error complaining about one of the fields taht I removed not being there ... (venv) localhost:mainsite_project davea$ python manage.py migrate mainsite Operations to perform: Apply all migrations: mainsite Running migrations: Applying mainsite.0019_auto_20190401_2139...Traceback (most recent call last): … -
Django - Simple query after using Serializer
I serialized my tables as outlined here: serializing tables. The output of this serialization was a JSON object that contain the queryset I wanted that used all of my tables. It renders perfectly on the template. Now, I need to pass the values from only one table as JSON to the template to create a select option menu using AJAX, but when I try to pass the id and category fields for that one table the Response passes the entire queryset I got when I serialized the tables. The queryset does not include all the options in the category table, only the ones that have been use in at least one entry. So, I need a new query that contains only the values in the category table. I tried this: Serializing Django objects data = serializers.serialize('json', Model.objects.all(), fields=('name','category')) return HttpResponse(data, safe=False) And it gave me the whole query set from earlier. I tried: data = serializers.serialize('json', Model.objects.all()) return HttpResponse(data, safe=False) And I got the full queryset again. I tried: data = Model.objects.all() return JsonResponse(data, safe=False) And: data = list(Model.objects.values()) return JsonResponse(data, safe=False) I get the full queryset. How can I query only the values in one table after serializing? Thanks! -
Django third party library url pattern before custom url pattern? (url pattern order)
Using Django (REST Framework) this is my root url conf : ... (imports) urlpatterns = [ re_path(r"^confirm-email/(?P<key>[-:\w]+)/$", accounts_views.email_verification, name="account_confirm_email"), path('admin/', admin.site.urls), path('request/', include('request.urls')), path('rest-auth/', include('rest_auth.urls')), path('rest-auth/registration/', include('rest_auth.registration.urls')), re_path(r'^account-confirm-email/', TemplateView.as_view(), name='account_email_verification_sent'), ] now, I am using the django-rest-auth library for authentication. This library sends a email to the user after they submit the registration form, for the purpose of activating the user's email address. In this email is a link, which is obtained by reversing an url pattern, the url pattern named: account_confirm_email the django-rest-auth library comes with it's own url pattern named account_confirm_email, in the following file, to be precise: python3.7/site-packages/rest_auth/registration/urls.py: ... (imports) urlpatterns = [ ... url(r'^account-confirm-email/(?P<key>[-:\w]+)/$', TemplateView.as_view(), name='account_confirm_email'), ] I expect my own url pattern to be the one that is reversed, not the rest-auth one, since mine comes first in order. As the Django docs state: Django runs through each URL pattern, in order, and stops at the first one that matches the requested URL. https://docs.djangoproject.com/en/2.2/topics/http/urls/ But in practice the rest-auth pattern is the one that is being reversed, why does this happen? To be complete, I see that the Django docs also say: Django determines the root URLconf module to use. Ordinarily, this is the value … -
How to get latest and earliest from a django QuerySet
In my django app, there are a few different ways that I get a QuerySet object of the same model. I would like to use one function to render the data -- and this has been working fine, until I decided to add both earliest and latest time to display on top of the list. Here's my latest attempt: def render_list(request, objList): latest = earliest = None if objList: latest = objList.latest('time').time earliest = objList.earliest('time').time context = {'objList': objList, 'earliest': earliest, 'latest': latest, } return render(request, 'list.html', context) This produces the error message: TypeError: Cannot reverse a query once a slice has been taken. Is there a way to get around this problem? -
How to prevent non logged in users from viewing a context_processor
Im getting an error of 'AnonymousUser' object is not iterable from this code: context_proccesors.py def subscriptions(request): context = { 'mysubs': Subscription.objects.filter(user=request.user, is_active=True) } return context How can I exclude this from being seen by non logged in users. -
Create models in Django using AWS S3 data
I would like to create models in Django using existing data in AWS S3 my models.py file class Video(models.Model): video_name = models.CharField(max_length=2000) video_url = models.CharField(max_length=2000, unique=True) my object creater function def create_model(**kwargs): return Video.objects.create(**kwargs) I can access my bucket using for s3_object_mp4 in my_bucket.objects.all(): path_mp4, key_mp4 = os.path.split(s3_object_mp4.key) create_model(video_name=str('key_mp4'), video_url='??') How can I pass the url of the video stored in aws s3 in the to be created model so I can access the video from my html using the following ? <video controls> <source src="{{ detailedview.video_url }}"> </video> -
<QuerySet ... > ... must be a ... instance | How to get data from forms using the formset?
There is a ProductCreateForm form. Need to add the SpeciallyPriceForm form to it. As I understand it, this is solved with the help of formset. There is a CBV view with a formset (maybe wrong). If I understand correctly, it is necessary to form the main form with formset in the get method, and then process them in the post method... def get_context_data(self, *args, **kwargs): ctx=super(ProductsCreate, self).get_context_data(*args, **kwargs) ctx['special_form'] = SpeciallyPriceForm() return ctx def get(self, request, *args, **kwargs): self.object = None if kwargs.get('slug'): category = Category.objects.filter(slug=kwargs.get('slug')).first() self.initial.update({'category': category}) return self.render_to_response(self.get_context_data()) def post(self, request, *args, **kwargs): self.object = None form = self.get_form() special_form = SpeciallyPriceForm(self.request.POST) print(special_form) if form.is_valid() and special_form.is_valid(): return self.form_valid(form) else: return self.form_invalid(form) All the fields are rendered, but there is a problem with the fact that when I try to view the data from the ProductCreateForm form, I get an error Cannot assign ", ]>": "Product.category" must be a "Category" instance. The problem is that in the form I refer to entries from the category table, but I refer not directly, but through the providers table as follows. def __init__(self, *args, **kwargs): user = self.request.user provider = Provider.objects.filter(user=user.id).last() self.fields['category'] = ModelMultipleChoiceField(queryset=provider.category.all()) Provider has MTM connection with Category. The … -
Django + Celery with long-term scheduled tasks
I'm developing a Django app which relies heavily on Celery task scheduling, using Redis as backend. Tasks can be set to run at a large periods of time, as well as in a few seconds/minutes. I've read about Redis visibility timeout and consequences of scheduling tasks with timedelta greater than visibility timeout (I'm also in the process of dealing with it in a previous project), so I'm interested if there's anything neater than my solution, which is to have another "helper" task run 5 minutes before the "main" one needs to be executed, scheduling the "main" task to run in required time, storing task id in DB, and then checking in "main" task if the stored task id is the one that is being run. The last part (with task id storing) is required as multiple runs of "helper" task could spawn a lot of "main" task instances, but with this approach each will have different task id. I really hate how that approach sounds and how it works, as if the task is scheduled to be run a month from current time, "helper" and "main" tasks are executed up to a hundred times. I also know that it's an … -
Django2 ListView using two models
I want to access two models from ListView in order to show data in a template_list models.py class MdCategoria(models.Model): name = models.CharField( max_length=100, verbose_name='Nombre', ) class MdEntrada(models.Model): categories = models.ManyToManyField( MdCategoria, verbose_name='Categorías', ) view.py class VwCategoria(BaseView, ListView): template_name = 'ap_blog/categoria.html' model = MdEntrada ¿ How to set query access to MdCategoria from VwCategoria ? ¿ How to show MdCategoria and MdEntrada datas using template tags in categoría.html ? -
How to use DRF serializers with Grapahene
I am following this tutorial for using Graphene with Django, and everything was going smooth, until I reached the Integration with Django Rest Framework section. This section says that you can reuse DRF serializers with Graphene, by creating serializers clones, but it doesn't say what to do with such clones in order to reuse DRF serializers with Graphene. This are my serializers and clones: from rest_framework import serializers from graphene_django.rest_framework.mutation import SerializerMutation from GeneralApp.models import Airport from ReservationsManagerApp.serializers import ReservationSerializer from ReservationsManagerApp.models import ReservationComponent, ReservationHotel, ReservationRoundtrip, ReservationTransfer, ReservationTour, ReservationService, Hotel class ReservationMutation(SerializerMutation): class Meta: serializer_class = ReservationSerializer class ReservationComponentGraphSerializer(serializers.ModelSerializer): component = serializers.SerializerMethodField() class Meta: model = ReservationComponent fields = ('id', 'reservation', 'dertour_bk', 'day', 'content_type', 'object_id', 'comment', 'is_invoiced', 'component') def get_component(self, instance): components_models = { 'reservationhotel': ReservationHotel, 'reservationroundtrip': ReservationRoundtrip, 'reservationtransfer': ReservationTransfer, 'reservationtour': ReservationTour, 'reservationservice': ReservationService, } component = components_models[instance.content_type.model].objects.get(id=instance.object_id) return self.get_component_string(instance.content_type.model, component) def get_component_string(self, component_model, component): components_get_string = { 'reservationhotel': self.get_hotel_string, 'reservationroundtrip': self.get_roundtrip_string, 'reservationtransfer': self.get_transfer_string, 'reservationtour': self.get_tour_string, 'reservationservice': self.get_service_string, } return components_get_string[component_model](component): def get_hotel_string(self, component): return component.hotel.name def get_roundtrip_string(self, component): return component.roundtrip.name def get_transfer_string(self, component): origin_str = self.get_place_str('origin', component) destination_str = self.get_place_str('destination', component) return "{} => {}".format(origin_str, destination_str) def get_place_str(self, case, component): places_models = { 'airport': Airport, 'hotel': Hotel, } if … -
Python Django Invalid Input Syntax Error for Int even though it isn't supposed to be an integer
I am making an e-commerce app using Python, Django 2.1, and PostgreSQL. When I click on one of the categories to show products specific to that category, it tells me that I have a data error. Apparently, in the URL, there is a string when there is supposed to be an integer. I don't understand this. Please help I have tried many different things, but none seem to work. My URL Patterns: path('products/phones/', product_views.CategoryDetailView.as_view(template_name='products/category_details/phones.html'), name='phones'), path('products/laptops/', product_views.CategoryDetailView.as_view(template_name='products/category_details/laptops.html'), name='laptops'), path('products/desktops/', product_views.CategoryDetailView.as_view(template_name='products/category_details/desktops.html'), name='desktops'), path('products/keyboards/', product_views.CategoryDetailView.as_view(template_name='products/category_details/keyboards.html'), name='keyboards'), path('products/mice-and-mouse-pads/', product_views.CategoryDetailView.as_view(template_name='products/category_details/mice.html'), name='mice'), path('products/headsets/', product_views.CategoryDetailView.as_view(template_name='products/category_details/headsets.html'), name='headsets'), path('products/printers-scanners-and-fax/', product_views.CategoryDetailView.as_view(template_name='products/category_details/printers.html'), name='printers'), path('products/consoles/', product_views.CategoryDetailView.as_view(template_name='products/category_details/consoles.html'), name='consoles'), path('products/misc/', product_views.CategoryDetailView.as_view(template_name='products/category_details/misc.html'), name='misc'), The error received is: django.db.utils.DataError: invalid input syntax for integer: "Phones" LINE 1: ...s_product" WHERE "products_product"."category_id" = 'Phones' -
Delete certain django app from a django project on heroku and exclude it from future push
In my django project named website I have two apps app1 & app2 . I want to keep app2 accessible only through my local machine. I dont want app2 to be publicly accessible online through my website. I have already pushed my entire website to heroku. So how can I delete app2 from heroku website and avoid pushing app2 to heroku in future. I have tried following things: Added app2/ to .gitignore. So future changes are avoided. But current version of app2 still exist on heroku website. I deleted app2 on local machine and tried to push the changes, but I got error in static collection saying no app named app2 exists. I would also like to avoid having Django's default admin functionality available through my website. I would like to keep it local too. Thanks -
I got error when i try to connect my django with mysql xampp server
Following error occurs, when i try to run this command - python manage.py migrate Traceback (most recent call last): File "C:\Users\Sazzad\Anaconda3\envs\GOT\lib\site-packages\django\db\backends\base\base.py", line 216, in ensure_connection self.connect() File "C:\Users\Sazzad\Anaconda3\envs\GOT\lib\site-packages\django\db\backends\base\base.py", line 194, in connect self.connection = self.get_new_connection(conn_params) File "C:\Users\Sazzad\Anaconda3\envs\GOT\lib\site-packages\django\db\backends\mysql\base.py", line 227, in get_new_connection return Database.connect(**conn_params) File "C:\Users\Sazzad\Anaconda3\envs\GOT\lib\site-packages\MySQLdb__init__.py", line 84, in Connect return Connection(*args, **kwargs) File "C:\Users\Sazzad\Anaconda3\envs\GOT\lib\site-packages\MySQLdb\connections.py", line 164, in init super(Connection, self).init(*args, **kwargs2) MySQLdb._exceptions.OperationalError: (1045, "Access denied for user 'sazzad'@'localhost' (using password: YES)") The above exception was the direct cause of the following exception: Traceback (most recent call last): File "manage.py", line 15, in execute_from_command_line(sys.argv) File "C:\Users\Sazzad\Anaconda3\envs\GOT\lib\site-packages\django\core\management__init__.py", line 381, in execute_from_command_line utility.execute() File "C:\Users\Sazzad\Anaconda3\envs\GOT\lib\site-packages\django\core\management__init__.py", line 375, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "C:\Users\Sazzad\Anaconda3\envs\GOT\lib\site-packages\django\core\management\base.py", line 316, in run_from_argv self.execute(*args, **cmd_options) File "C:\Users\Sazzad\Anaconda3\envs\GOT\lib\site-packages\django\core\management\base.py", line 350, in execute self.check() File "C:\Users\Sazzad\Anaconda3\envs\GOT\lib\site-packages\django\core\management\base.py", line 379, in check include_deployment_checks=include_deployment_checks, File "C:\Users\Sazzad\Anaconda3\envs\GOT\lib\site-packages\django\core\management\commands\migrate.py", line 59, in _run_checks issues = run_checks(tags=[Tags.database]) File "C:\Users\Sazzad\Anaconda3\envs\GOT\lib\site-packages\django\core\checks\registry.py", line 71, in run_checks new_errors = check(app_configs=app_configs) File "C:\Users\Sazzad\Anaconda3\envs\GOT\lib\site-packages\django\core\checks\database.py", line 10, in check_database_backends issues.extend(conn.validation.check(**kwargs)) File "C:\Users\Sazzad\Anaconda3\envs\GOT\lib\site-packages\django\db\backends\mysql\validation.py", line 9, in check issues.extend(self._check_sql_mode(**kwargs)) File "C:\Users\Sazzad\Anaconda3\envs\GOT\lib\site-packages\django\db\backends\mysql\validation.py", line 13, in _check_sql_mode with self.connection.cursor() as cursor: File "C:\Users\Sazzad\Anaconda3\envs\GOT\lib\site-packages\django\db\backends\base\base.py", line 255, in cursor return self._cursor() File "C:\Users\Sazzad\Anaconda3\envs\GOT\lib\site-packages\django\db\backends\base\base.py", line 232, in _cursor self.ensure_connection() File "C:\Users\Sazzad\Anaconda3\envs\GOT\lib\site-packages\django\db\backends\base\base.py", line 216, in ensure_connection self.connect() File "C:\Users\Sazzad\Anaconda3\envs\GOT\lib\site-packages\django\db\utils.py", line 89, in exit raise … -
Django Composite Foreign Key
Is there a way to create a composite foreign in Django and use the key to create and update certain entries? I have looked at the package django-composite-foreignkey. However, it doesn't provide a way to use the key for creating/updating -
getting error <Follower: Follower object (None)> instance isn't saved. Use bulk=False or save the object first
I am trying to create a follow functionality in django. I am using the following model. I would like to test that this works on django manage.py shell. When I do the relevant imports and run user1.following.add(Follower(following=user2)) I get the following error instance isn't saved. Use bulk=False or save the object first. what is the reason for this models.py class Follower(models.Model): follower = models.ForeignKey(User, related_name='following',on_delete=models.PROTECT) following = models.ForeignKey(User, related_name='followers',on_delete=models.PROTECT) class Meta: unique_together = ('follower', 'following') def __unicode__(self): return u'%s follows %s' % (self.follower, self.following) -
Django Dependent Dropdown Not Working on First Save
Just some background info: I have two models Property and Unit, and as you probably guessed, each unit belongs to a property. Finally another model named Tenant has a property and Unit. Here is what my forms.py looks like: class AssignPropertyForm(forms.ModelForm): class Meta: model = Tenant fields = ('prop', 'unit') def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.fields['prop'].queryset = Property.objects.filter(owner=self.instance.landlord) self.fields['unit'].queryset = Unit.objects.none() if 'prop' in self.data: try: print(self.data) prop_id = int(self.data.get('prop')) self.fields['unit'].queryset = Unit.objects.filter(prop__id=prop_id) except (ValueError, TypeError): pass # invalid input from the client; ignore and fallback to empty unit queryset elif self.instance.unit != None: # Triggered when a tenant already has a unit assigned # and you are looking to make an edit try: prop_id = self.instance.prop.id self.fields['unit'].queryset = Unit.objects.filter(prop__id=prop_id) except: pass If I am editing an existing form and make a change to a unit, it saves just fine. However, I am assigning a property for the first time I get: Select a valid choice. That choice is not one of the available choices. with regards to the unit field. Any idea on what I'm doing wrong here? Thanks. -
MultiValueDictKeyError at /product/create/ 'icon'
when i upload icon and image then error come MultiValueDictKeyError at /product/create/ 'icon' MultiValueDictKeyError at /product/create/ 'icon' Request Method: POST Request URL: http://127.0.0.1:8000/product/create/ Django Version: 2.2a1 Exception Type: MultiValueDictKeyError Exception Value: 'icon' Exception Location: C:\Users\Rohit\Anaconda3\lib\site-packages\django-2.2a1-py3.7.egg\django\utils\datastructures.py in getitem, line 80 Python Executable: C:\Users\Rohit\Anaconda3\python.exe Python Version: 3.7.0 def create(request): if request.method == 'POST': if request.POST['title'] and request.POST['body'] and request.POST['url'] and request.POST['icon'] and request.POST['image']: product=Product() product.title=request.POST['title'] product.body=request.POST['body'] if request.POST['url'].startswith('https//') or request.POST['url'].startswith('http//'): product.url=request.POST['url'] else: product.url= 'https//'+ request.POST['url'] product.image = request.FILES['image'] product.icon = request.FILES['icon'] product.pub_date=timezone.datetime.now() product.hunter = request.user product.save() return redirect('home') else: return render(request, 'products/create.html',{'error': 'please fill all the detail'}) -
django.urls.exceptions.NoReverseMatch: Reverse for 'InputData' not found. 'InputData' is not a valid view function or pattern name
I can't seem to solve this NoReverseMatch error. Urls.py: from django.conf.urls import url, include from . import views app_name= 'service-development' urlpatterns = [ url(r'^$', views.index, name='index'), url(r'^choice/(?P<element_id>[0-9]+)/(?P<session_id>[0-9]+)$', views.choice, name='choice'), url(r'^message/(?P<element_id>[0-9]+)/(?P<session_id>[0-9]+)$', views.message_presentation, name='message-presentation'), url(r'^start/(?P<voice_service_id>[0-9]+)$', views.voice_service_start, name='voice-service'), url(r'^start/(?P<voice_service_id>[0-9]+)/(?P<session_id>[0-9]+)$', views.voice_service_start, name='voice-service'), url(r'^user/register/(?P<session_id>[0-9]+)$', views.KasaDakaUserRegistration.as_view(), name = 'user-registration'), url(r'^language_select/(?P<session_id>[0-9]+)$', views.LanguageSelection.as_view(), name = 'language-selection'), url(r'^record/(?P<element_id>[0-9]+)/(?P<session_id>[0-9]+)$', views.record, name='record'), url(r'^inputdata/(?P<element_id>[0-9]+)/(?P<session_id>[0-9]+)$', views.InputData, name='inputdata') ] input.xml {% extends "base.xml" %} {% block content %} <grammar mode="dtmf" version="1.0" root="AddInput"> <rule id="zerotonine" scope="public"> <one-of> <item repeat="0-"> <one-of> <item>0</item> <item>1</item> <item>2</item> <item>3</item> <item>4</item> <item>5</item> <item>6</item> <item>7</item> <item>8</item> <item>9</item> </one-of> </item> </one-of> </rule> </grammar> <form id="input_form"> <input name="input" beep="true" dtmfterm="true"> <prompt> <audio src="{{ voice_label }}"/> <property name="termchar" value="#" /> </prompt> {% if record.ask_confirmation %} <field name="confirm"> <prompt> <audio src="{{ask_confirmation_voice_label}}"/> </prompt> <grammar xml:lang="en-US" root = "MYRULE" mode="dtmf"> <rule id="MYRULE" scope = "public"> <one-of> <item>1</item> <item>2</item> </one-of> </rule> </grammar> <filled> <if cond="confirm == '1'"> <prompt> <audio src="{{final_voice_label}}"/> </prompt> <assign name="redirect" expr="'{{ redirect_url }}'"/> <submit next="{{ url }}" enctype="multipart/form-data" method="post" namelist="redirect recording"/> </if> <if cond="confirm == '2'"> <goto next="{{ url }}"/> </if> </filled> </field> {% endif %} <block> <prompt> <audio src="{{final_voice_label}}"/> </prompt> <goto next="{{ redirect_url }}" /> </block> </form> {% endblock %} vse_input.py: from django.shortcuts import render, get_object_or_404, get_list_or_404, redirect from ..models import * def input_get_redirect_url(input_element, session): … -
How to fix a global variable problem into django model?
Hello to everyone, I am facing a basic problem since few day ago so now I have decided to ask a question after tried to do many many example but stilled have the same issue with my model. I am using a function to get user ip address into my django model for me to determine the user country and more others and so far nothing seem to work, I have also used a Class but I stilled have the same problem. Please any help will be highly appreciate. this is my function: the variable ip for the beginning ip_address_one = '0.0.0.0' def take_ip(request): global ip_address_one x_forwarded_for = request.META.get('HTTP_X_FORWARDED_FOR') if x_forwarded_for: ip = x_forwarded_for.split(',')[0] ip_address_one = ip else: ip = request.META.get('REMOTE_ADDR') ip_address_one = ip it's still have the same value '0.0.0.0' nothing changed print(ip_address_one) reader = GeoIP2() reader.country_name(ip_address_one) current_country = reader.country_name(ip_address_one) And when i callled the function like this: take_ip() I got an error and when I put a request like this take_ip(request) I got request is not defined. I done this to my model to determine the country with geoip2 Please help thank you. -
How to set different paginate_by depending on different requests?
I'm using Django pagination so that I can do view more thing in my website. The below code snippet is what I tried. The page first shows up it shows 7 articles and then shows 6 articles per each view more button clicked. The below way didn't work. How can I set different paginate_by values? views.py class ArticleListView(ListView): model = Article paginate_by = 7 def get_template_names(self): if self.request.is_ajax(): self.paginate_by = 6 return ['blogs/components/articles.html'] return ['blogs/index.html'] -
Django YouTube API Upload fails with iPhone
I can upload videos to YouTube through my Django application, but only when they are uploaded from my laptop. YouTube gives me a "Processing abandoned" error when I upload the same video through my iPhone. I am running Ubuntu 16.04.3 with Django version 1.11.20 and Python 2.7. I am using a function in my views to receive the uploaded file, and, if it is over 2.5 megabytes, grab the file from the /tmp directory, and if it is under 2.5 megabytes, process the file from memory. This works when I upload video files from my laptop, but it fails when I upload video files from my iPhone. To be clear, I don't get errors from Django/Python. The file seems to upload, process, and delete just fine. But after YouTube receives it, I go into my YouTube Studio, and it gives me a "Processing abandoned. This video could not be processed," error. def upload_to_youtube(request): if request.method == 'POST' and request.FILES['video']: video_file = request.FILES['video'] if video_file.size >= 2621440: fname = request.FILES['video'].file.name storage = DjangoORMStorage(CredentialsModel, 'id', request.user.id, 'credential') credentials = storage.get() client = build('youtube', 'v3', credentials=credentials) body = {...} with tempfile.NamedTemporaryFile('wb', suffix='yt-django') as tmpfile: with open(fname, 'rb') as fileobj: tmpfile.write(fileobj.read()) insert_request = client.videos().insert( … -
Authentication issues with django-webpack-loader with vuejs and django restframework and restauth
I created a frontend with vue.js using vue cli and webpack and the backend using django restframework where I am also implementing social authentication for google using restauth. Before I used the django webpack, the login and logout would work fine and as expected. (I should mention that I was using tokenauthentication) in my settings.py, file I had both the sessionauthentication as well as tokenauthentication enabled in the restframework authentication possibilities. The two settings being enabled never caused any trouble. However, after using the django webpack loader to render the frontend vue files using django templates, I would continuously get an error that said my csrf token was not present. The login would work fine in this case if I removed the sessionauthentication option out of the settings.py file however. Does anyone know why this is happening? https://medium.com/@rodrigosmaniotto/integrating-django-and-vuejs-with-vue-cli-3-and-webpack-loader-145c3b98501a I used the above blog to implement the webpack loader functionality I removed the 'rest_framework.authentication.SessionAuthentication', line from my settings.py after using the django-webpack-loader and the issue was resolved REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': ( 'rest_framework.authtoken', 'rest_framework.authentication.BasicAuthentication', 'rest_framework.authentication.SessionAuthentication', ) } I basically changed it like below: REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': ( 'rest_framework.authtoken' 'rest_framework.authentication.BasicAuthentication', ) } -
Why migrations is not working neither it creates migrations directory in django app
It was working fine I first installed the app. After that i deleted my db.sqlite migrations and pycache file. Then I tried to migrate again all the default migrations worked except for the Post model which is in the postapp. I tried several time to migrate, every time it says no change detected and doesn't create any migrations directory after running python manage.py showmigrations I get something like this it does not mentions post app name or any migrations related to post app admin [X] 0001_initial [X] 0002_logentry_remove_auto_add [X] 0003_logentry_add_action_flag_choices auth [X] 0001_initial [X] 0002_alter_permission_name_max_length [X] 0003_alter_user_email_max_length [X] 0004_alter_user_username_opts [X] 0005_alter_user_last_login_null [X] 0006_require_contenttypes_0002 [X] 0007_alter_validators_add_error_messages [X] 0008_alter_user_username_max_length [X] 0009_alter_user_last_name_max_length [X] 0010_alter_group_name_max_length [X] 0011_update_proxy_permissions contenttypes [X] 0001_initial [X] 0002_remove_content_type_name sessions [X] 0001_initial How can I solve this it happens to me in every Django project. it needs to be fixed -
How to get a value from a static page and post it into a model
I have showed the values {{ p.emri }} and {{ p.cmimi }} which are in the "Produkte" model onto my Browse.html. So far so good , but now I'm trying to write a function in views.py to get this values and post them into another model named "AddToCart" when i press the submit button. I'm trying to write the views.py function where i'm thinking of getting the values first with a "GET" method and store them in variables then using a "POST" method to save those variables into the model "AddToCart" This is the 'Browse.html' file where the values are shown from model "Produkt" {% for p in produktet %} <div class="col-md-3 col-sm-12 col-xs-12 on-over" style="..."> <img class..." src="{{ p.foto }}"> <label class="label-ge">{{ p.emri }}</label> <p><label style="...">{{ p.cmimi }} LEK</label></p> <h4>Pershkrimi</h4> <p>{{ p.pershkrimi }}</p> <button class="btn..." style="...">Add to Cart</button> </div> {% endfor %} This are the "Produkt" and "AddToCart" models class Produkte(models.Model): emri = models.CharField(max_length=50) pershkrimi = models.CharField(max_length=500) cmimi = models.IntegerField() foto = models.CharField(max_length=500) kategori = models.ForeignKey(Kategorite, on_delete = models.DO_NOTHING) def __str__(self): return self.emri class AddToCart(models.Model): id = models.AutoField(primary_key=True, unique=True) id_product = models.ForeignKey(Produkte, on_delete = models.DO_NOTHING) quantity = models.IntegerField() id_user = models.ForeignKey(User, on_delete = models.DO_NOTHING) orderd = models.BooleanField(default=False) @property def …