Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
NoReverseMatch - reverse for ' ' with keyword arguments 'pk' not found
im pretty sure this is a simple error but I cant seem to figure it out. The error states that the keyword arguments are not found but i have them in the the html. here is error: NoReverseMatch at /questions/questionupdate/user2-question3/4/ Reverse for 'detail' with keyword arguments '{'pk': 4}' not found. 1 pattern(s) tried: ['questions/questiondetail/(?P<slug>[\\w-]+)/(?P<pk>\\d+)/$'] Request Method: GET Request URL: http://127.0.0.1:8000/questions/questionupdate/user2-question3/4/ Django Version: 1.11 Exception Type: NoReverseMatch Exception Value: Reverse for 'detail' with keyword arguments '{'pk': 4}' not found. 1 pattern(s) tried: ['questions/questiondetail/(?P<slug>[\\w-]+)/(?P<pk>\\d+)/$'] file structure: project: UserTest --->app:accounts --->app:questions models.py class Question(models.Model): class Meta: ordering = ['-date_updated'] user = models.ForeignKey(User, related_name="question") # completedTODO: get user working^ question = models.TextField(blank=False, null=False) # unique=True, question_html = models.TextField(blank=False, null=False) answer = models.TextField(blank=False, null=False) answer_html = models.TextField(blank=False, null=False) slug = models.SlugField(unique=True, default='') tags = TaggableManager() def __str__(self): return self.question def save(self, *args, **kwargs): self.question_html = misaka.html(self.question) self.answer_html = misaka.html(self.answer) super().save(*args, **kwargs) def get_absolute_url(self): return reverse( "questions:detail", kwargs={ # "slug": self.slug, "pk": self.pk } ) urls.py i am trying to pass both slug and pk to url url(r'questiondetail/(?P<slug>[\w-]+)/(?P<pk>\d+)/$', views.QuestionDetail.as_view(), name='detail'), url(r'questionupdate/(?P<slug>[\w-]+)/(?P<pk>\d+)/$', views.QuestionUpdate.as_view(), name='update'), views.py class QuestionDetail(generic.DetailView): model = models.Question class QuestionUpdate(generic.UpdateView): model = models.Question form_class = QuestionForm template_name = "questions/question_form_update.html" question_detail.html <h3><a href="#">{{ question.user }}</a></h3> <h3>{{ … -
Library for OpenID URL
I am a new in Python and Django world. I would like to make Authentication process using OpenID with Django framework like on livejournal.com by passing URL(user will do it). Can you give me name of the library which I can use to implement this kind of functionality? -
Django: Form has no attribute 'get'
i have a form that contains 3 fields : class AjoutBanque(forms.Form): nom=forms.CharField() agence=forms.CharField() rib=forms.IntegerField() my view : def AjoutBanq(request): if request.user.is_active : form2=AjoutBanque(request.POST) if form2.is_valid(): print("valid") clt= banque(nom=form2.cleaned_data.get('nom'),agence=form2.cleaned_data.get('agence'),rib=form2.cleaned_data.get('rib')) clt.save() return redirect('/banque/') when submiting my form it raises the error : 'AjoutBanque' object has no attribute 'get' i dont know where this error came from, do you have any idea ? Thank you for your help. -
Build a Backend that upload files to FTP
I have 2 mobile apps and a website that need a function that can upload some files in XML format to FTP. Hence I am thinking to build a backend that manipulates those XML files so that all 3 applications can use it. Should I be building a RESTful or SOAP API? -
Getting related objects using django ORM
models.py class Soldier(models.Model): name = models.CharField(...) added_by = models.ForeignKey('self') soldier_1 added soldier_2 soldier_2 added soldier_3 soldier_3 added soldier_4 How can I get all related soldier as soldier_1? Expected result: >>> related_soldiers = Soldier.objects.filter(added_by=...) >>> related_soldiers <QuerySet [<Soldier: soldier_2>, <Soldier: soldier_3>, <Soldier: soldier_4>]> -
Django HiddenField value generated on Views
models.py class Category(Model): name = models.CharField(max_length=45) class Animal(Model): name = models.CharField(max_length=45) codename = models.CharField(max_length=45) categories = models.ManyToManyField(Category) serializers.py class CategorySerializer(serializers.ModelSerializer): class Meta: model = models.Category fields = '__all__' class AnimalSerializer(serializers.ModelSerializer): codename = serializers.HiddenField(default="auto_replace_me") class Meta: model = models.Animal fields = '__all__' views.py class CategoryViewSet(ModelViewSet): queryset = models.Category.objects.all() serializer_class = serializers.CategorySerializer class AnimalViewSet(ModelViewSet, CreateModelMixin): queryset = models.Animal.objects.all() serializer_class = serializers.AnimalSerializer def create(self, request, *args, **kwargs): codename = generate_codename() # (1) external API request (with codename included on request) and returns a boolean `result` if result: # (2) calls create method from parent class BUT it needs to save the codename in database return super(AnimalViewSet, self).create(request, *args, **kwargs) else: return HttpResponseServerError() def generate_codename(): return ''.join([random.choice(string.ascii_letters) for n in range(10)]) Overview: need to generate a codename value for a hidden field in order to send it to an external API (1) and after that include the generated codename field in database (2). Issue: How can I send the generated codename (HiddenField) to database? -
django api deployed to google app engine error: 2005, "Unknown MySQL server host https://mythic-plexus-194517.appspot.com/products/
I'm trying to host a django-build api on google's app engine but i'm struggling to get it to work. This is the first time I'm deploying an app to production so apologies for the noob question. I've deployed the app and all works at the base domain https://mythic-plexus-194517.appspot.com, however, when I go to /products endpoint where the relevant information in my db is posted, I hit (2005, "Unknown MySQL server host 'mythic-plexus-194517:europe-west1:giftwiz-api' (38)"). I do not hit this error when I run python manage.py runserver. My app.yaml file: runtime: python27 api_version: 1 threadsafe: true handlers: - url: /static static_dir: static - url: /.* script: giftwiz_project.wsgi.application libraries: - name: django version: "latest" - name: MySQLdb version: "latest" env_variables: DJANGO_SETTINGS_MODULE: 'giftwiz_project.settings' database config in settings.py: if os.getenv('SERVER_SOFTWARE', '').startswith('Google App Engine'): # Running on production App Engine, so connect to Google Cloud SQL using # the unix socket at /cloudsql/<your-cloudsql-connection string> DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'HOST': 'mythic-plexus-194517:europe-west1:giftwiz-api', 'NAME': 'products', 'USER': 'xxxx', 'PASSWORD': 'xxxx', 'PORT': '3306' } } else: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'HOST': '127.0.0.1', 'PORT': '3306', 'NAME': 'products', 'USER': 'root', 'PASSWORD': os.environ.get('mysql_pass') } } and urls.py: from django.conf.urls import url, include from django.contrib import admin from rest_framework … -
how to use django-filters on django-tables2
This is my view: class PersonalView(SingleTableMixin, FilterView): model = Invoice template_name = 'klarsicht/index.html' table_class = InvoiceTable filterset_class = InvoiceFilter context_object_name = 'invoice' ordering = ['invoice_due_date'] def get_table_data(self): return Invoice.objects.filter(invoice_owner__username=self.request.user).order_by('i nvoice_due_date') Now, get_table_data does the right thing, the invoices are filtered according to the user. But, the InvoiceFilter(django_filters.FilterSet) does not work then. It does work, however, when I don't override get_table_data. Right now, the filters, which appear as normal and are passed normally, just don't filter. It always shows the data according to get_table_data, no matter which filter string I enter. How can I get it all? I want define my custum table data and have my defined filters work on that. -
Which is the easier and convenient way to make post methods for multiple model instances in django
I have an Employee class that has a couple of instances that are ForeignKeys. I am using django rest frame work and I have created also a serializer and the next step is to create a POST method to enable creating of an Employee. Which method can I use conveniently to achieve this? class Employee(models.Model): """ Model, which holds general information of an employee. """ user = models.OneToOneField(User,related_name='users', on_delete=models.CASCADE) photo_logo = models.FileField() phone_regex = RegexValidator(regex=r'^\+?1?\d{9,15}$', message="Phone number must be entered in the format: '+999999999'. Up to 15 digits allowed.") phone_number = models.CharField(validators=[phone_regex], max_length=17, blank=True) # validators should be a list company = models.ForeignKey( 'hr.Company', verbose_name='Company', related_name='companies', null=True, blank=True, ) marital_status = models.ForeignKey(MaritalStatus) identification_type = models.ForeignKey(IdentificationType) Serializers.py class EmployeeSerializer(serializers.ModelSerializer): designation = GroupListSerializer() # department = GroupListSerializer() # user = UserSerializer() # address = AddressSerializer() # em_contact = EmergencyContactSerializer() # address = EmergencyContactSerializer() class Meta: model = Employee fields = ['id','user','photo_logo','phone_number','dob', 'gender', 'hr_number', 'company', 'marital_status', 'identification_type', 'tax_id_number','joining_date', 'designation', 'department'] -
Django filter by query result
In my fixturesquery below you can see I am filtering by the results of the teamsquery, and it works, but only for the first result of the teamsquery. So it only outputs the fixtures for the first userteam__userID=request.user teamsquery = Team.objects.filter(userteams__userID=request.user) fixturesquery = Fixtures.objects.filter(Q(hometeamID=teamsquery) | Q(awayteamID=teamsquery)) How do i fix it so it outputs the fixtures for all the results of teamsquery? -
Django's is_ajax() request works during development but breaks in production due to "undefined responseJSON"
During development, I have an ajax method that works--it executes, posts to the backend, my Django view checks if is_ajax(), then return JsonResponse(). Back on the frontend, I dig into responseJSON to get my object. In a production environment, there is apparently no responseJSON. Why? Here's my ajax method: $(document).ready(function(){ var $myForm = $('.ajax-public-toggle-form') $myForm.change(function(event){ var $formData = $(this).serialize() var $endpoint = $myForm.attr('data-url') $.ajax({ method: "POST", url: $endpoint, data: $formData, success: handleFormSuccess, error: handleFormError, }) }) function handleFormSuccess(data, textStatus, jqXHR){ // no need to do anything here console.log(data) console.log(textStatus) console.log(jqXHR) } function handleFormError(jqXHR, textStatus, errorThrown){ // on error, reset form. raise validationerror $('#public_toggle_form_errors').text(jqXHR["responseJSON"]["public"]); $('#public_toggle_form_errors').show(); console.log(jqXHR) console.log(textStatus) console.log(errorThrown) $myForm[0].reset(); // reset form data // console.log(errors) } }) So I can still console.log(jqxhr) but it won't include the responseJSON object like it does during development. This is the Django view: class AjaxView(View): def post(self, request): if self.request.is_ajax(): if self.request.user.is_authenticated(): if self.request.user.profile.public: data = { 'message': "Allow button click" } return JsonResponse(data) else: data = { 'error': "ERRO HERE", 'message': "EORR MESG" } return JsonResponse(data, status=400) else: data = { 'message': "LOG IN" } return JsonResponse(data, status=400) The console will first output: jquery-3.3.1.min.js:2 POST https://paira.herokuapp.com/profile/public_toggle 403 (Forbidden) then: project.js:52 Uncaught TypeError: Cannot read … -
How to add a conditional field in a Django model?
Basically, what I want is a field to be available if a condition is met, so something like this: class ConditionalModel(models.Model): product = models.ForeignKey(product, on_delete=models.CASCADE) if category == "laptop": cpu_model = models.CharField(max_length=200) so if I were to go to the Django admin page and create an instance of the model and then choose "laptop" as the product from the drop-down list of existing "products", a new field would be available. I couldn't find anything about this in the documentation, so I'm wondering whether it's even possible. -
Django Mongo SQLDecodeError at /admin/
I have been experimenting with mongodb with Django. I created a super user, and then proceeded to http://localhost:8000/admin/ to login. Upon entering my credentials, and submitting them, the error given at the end of this post occurred. I have 2 other apps in this project and have also commented the line where the admin can register the model in appname/admin.py, i.e.: #admin.site.register(Tweet) How can I fix this? If you would like any further information about the code or from certain files please let me know and I will edit it in :) I assume the error is caused with the way mongo and django is workign together but have no idea how to correct it. I am sure the python installation, and routes all work correctly as they were configured with the assistance of the department admins. NOTE: some of the routes are due to custom installation of Python in case it seems extremely weird. I am using a Department machine to do my work, hence the paths. Relevant Versions of modules/software: [GCC 4.8.5 20150623 (Red Hat 4.8.5-16)] on linux python (3.6.4) Django (2.0.3) MongoDB shell version: (2.6.12) mongod --version results in: db version v2.6.12 pymongo (3.6.1) sqlparse (0.2.4) djongo … -
How to hide Django form fields using JavaScript, Jquery etc
I would like to dynamically hide form fields. The user should be able to select the component type, which could be a VALVE in which case the user should specify the Kv value and the DI and length fields should be hidden. Or the user could select the PIPE component type in which case the user should specify the inner diameter (DI) and length of the pipe and the k_v field should be hidden. The model is defined as follows: class Component(models.Model): COMPONENT_TYPE_CHOICES = ( (1, 'k_v'), (2, 'pipe') ) circuit = models.ForeignKey('circuit.Circuit', related_name='components', on_delete=models.CASCADE) component_type = models.IntegerField(default=1, choices = COMPONENT_TYPE_CHOICES) component_name = models.CharField(max_length=200) branch_number_collectors = models.IntegerField(default=4) # Hide if component_type==2 k_v = models.FloatField(default=1) # Hide if component_type==1 DI = models.FloatField(default=0.025) length = models.FloatField(default=1) # Calculated properties branch_volumetric_flow_rate = models.FloatField(default=0) branch_mass_flow_rate = models.FloatField(default=0) velocity = models.FloatField(default=0) reynolds = models.FloatField(default=0) friction_coefficient = models.FloatField(default=0) pressure_loss = models.FloatField(default=0) @classmethod def create( cls, circuit, ..., The forms.py is as follows: class ComponentForm(forms.ModelForm): class Meta: model = Component fields = [ 'component_type', 'component_name', 'branch_number_collectors', 'k_v', 'DI', 'length' ] The simplified Django template is as follows: {% block content %} <form method='POST'> {% csrf_token %} {{ form.as_p }} <button type='submit'>Save</button> </form> {% endblock %} -
my session key doesn't exist even it is stored in DB
when i tried to store the session key in the database, it is successfully done and I can see it from the admin portal, I have used the following code to store the session_key if not kwargs.get(('request')).session.session_key: kwargs.get(('request')).session.save() UserSession.objects.create( user=instance, IPAddress=get_IP(kwargs.get('request')), sessionkey=kwargs.get(('request')).session.session_key) The following is my model class UserSession(models.Model): user = models.ForeignKey(User, blank=True, null=True, on_delete=models.CASCADE) IPAddress = models.CharField(max_length=225) sessionkey=models.CharField(max_length=100,blank=True,null=True) timestamp = models.DateTimeField(auto_now_add=True) active=models.BooleanField(default=True) ended=models.BooleanField(default=False) **but when i tried to access it using ** from django.contrib.sessions.models import Session Session.objects.get(pk='0wjxg94sr5aosndyit7ki1dhuiuw6ovg') **it gave me the following error ** django.contrib.sessions.models.DoesNotExist: Session matching query does not exist **and indeed didn't find my session_key when i used the following command ** Session.objects.all() -
django-alexa unable to read intents
As per the Tutorial given by django-alexa When i place alexa.py in my project folder myalexa/ db.sqlite3 manage.py insurance/ admin.py alexa.py apps.py models.py tests.py views.py __init__.py migrations/ __init__.py myalexa/ .gitignore LICENSE README.md settings.py urls.py wsgi.py __init__.py and i did \myalexa>python manage.py alexa_intents { "intents": [ { "intent": "LaunchRequest", "slots": [] }, { "intent": "CancelIntent", "slots": [] }, { "intent": "StopIntent", "slots": [] }, { "intent": "HelpIntent", "slots": [] }, { "intent": "SessionEndedRequest", "slots": [] } ] } as per the tutorial it should give my intents that are present in my alexa.py but is still give me the old content what am i doing wrong. and also how do i find my ALEXA_APP_ID_my_app=as per the tutorial amzn1.echo-sdk-ams.app.e18a3326-4775-45f2-83n0-5eeg03832401 but what i get is "applicationId": "amzn1.ask.skill.6aad0e83-2b02-4c83-9063-58374b780c7d" Thanks in advance -
ö intead of letter in django template
I am using django 1.11.2 and ckeditor. Here text is displaing: <p>{{ object.text|striptags }}</p> I am using striptags because I have link in link, I mean: <a> <a></a> </a> I have problem with content, instead letters (German charactes) I got: &ouml, &auml. I was using also <p>{{ object.text|striptags|safe }}</p> but I had space in stings. -
Django: Pass URL parameter to context_data in generic.CreateView
Maybe u will help me, hi. I create two url path. path('addhours/<int:jobNr>/', views.AddHoursView.as_view(), name='addhours'), path('addhours/', views.AddHoursView.as_view(), name='addhours'), And CreateView for this paths. class AddHoursView(generic.CreateView): template_name = "worktime/addhours.html" form_class = AddHoursForm success_url = reverse_lazy('worktime:myjobs') def get_form_kwargs(self): # pass "jobNr" keyword argument with the current url to form kwargs = super(AddHoursView, self).get_form_kwargs() kwargs['jobNr'] = self.kwargs.pop(JOB_PARAM, None) return kwargs And form, where number of fields depends from url if parameter exist. class AddHoursForm(forms.ModelForm): def __init__(self, *args, **kwargs): #Add jobworker field to from Worktime model if any jobNr pass in url #When in url will be parameter. Job foreignkey will be set by automat. self.jobNr = kwargs.pop('jobNr', None) super(AddHoursForm, self).__init__(*args, **kwargs) if not self.jobNr: self.fields['jobWorker'] = forms.ModelChoiceField(queryset=Job.objects.all()) class Meta: model = WorkTime fields = ['date', 'hours', 'description'] widgets = { 'date': forms.SelectDateWidget(empty_label=("Choose Year", "Choose Month", "Choose Day")) } Now i wanna have in AddHoursView context["foo"] = "bar" where /url/bar In AddHoursView in def context_data(self, **kw) self.request.Get give me empty QueryDict `self.kw['jobNr'] give me keyerror I need pass to url parameter if exist for pass this jobNr to template, so override form_valid it's not what i need. -
django_nose ignores wrapped tests
I have such kind of wrapper def external_services_mock(f): @patch('service.remote_call1') @patch('service.remote_call2') def wrapper(self, remote_call2_mock, remote_call1_mock, *args, **kwargs): remote_call1_mock.return_value = None def test_mocks(): return remote_call1_mock, remote_call2_mock f(self, test_mocks, *args, **kwargs) return wrapper and test: @external_services_mock def test_add_callback(self, test_mocks): remote_call1_mock, remote_call2_mock = test_mocks() // do smth // assert smth django_nose runner ignores wrapped tests, and normally runs regular Django version 2.0.2 django_nose 1.4.5 any ideas? -
Django: Accept zip file having multiple image files in it through a Django form as FileField and operate on it
Class X(models.Model): zip_file = models.FileField() Now, this zip_file is a zip having any number of images. I want to be able to extract all the images and save (to DB) them under the same X object i.e. the "primary key" is the same. I understand that the File is stored in the system and only a reference is stored in the DB and I am fine with it. I am unsure about what is the best practice to unzip the file at the server and save them one by one to the DB. One naive idea I have is using the "validators" to check the files and save them to DB but unsure if that is a best practice. Any help or suggestion is appreciated. :) -
Django template execute on only first occurance of match in a for loop
I have a video table with Foreign Keys that point to a document (multiple videos to one doc). I would like to check every element of that list, and on the first match with a query, enable an element (button that leads elsewhere). My attempts have been to use a for loop and then an if statement such that: {% for vid in doc.video_set.all %} {% if vid.query_data == 'match_term' %} <-- button/link stuff --> {% initialize variable %} {% endif %} {% endfor %} the idea being if I initialized a variable I could add if "and variable is None" to the if statement and prevent future displays. However, after trying to use "set" and "with" to intialize variables I have been greeted with little more than error messages that seem to indicate these methods dont exist. How would I effectively achieve this functionality. -
Delivery Rate is slow for RabbitMQ
We have a Django application. We are using celery as a worker for our application with RabbitMQ. There is a use case where: Our webapp submits a task to Queue1 and Queue1 has to create around 10 million jobs for Queue2 When Queue1 receives a task from webapp, it creates further jobs in its own queue in batches of 100k which will now be submitted to Queue2. The problem being faced: The rate of delivery is not going more than 15000/s on RMQ UI. and it is taking around 10 minutes for workers of Queue1 to submit 10 million jobs to Queue2. Is there a limit on RabbitMQ on the rate at which it can receive messages/jobs from celery or any other client? Any system limitations we can try to change? Any erlang setting that can help? Are there any limitations on celery for submitting tasks to RabbitMQ? I have seen that Google reached a rate of 1.4million/sec. I have also tried to cluster RMQ but is there a way to have multiple masters that can accept writes? -
Whta is the best way to distribute django based project?
I want to create a project that will include multiple apps that extend Django functionality for my needs and meet the following requirements: 1. I want to make it like a reusable Django package that will be possible to install with pip. It will be a small own framework for my new projects. 2. It should install all dependencies automatically(like Django and .etc). 3. I want to be able to continue working on the project and be able to update it on systems like GitHub or Bitbucket. I read the official documentation Django about writing reusable apps I tried to google this question and found some approach like this: http://racingtadpole.com/blog/reusable-django-apps/ but I'm not sure that it is an only one way(I mean that approach that was described in the comments). Maybe someone can share experience, how such problems were solved or what approaches could be used in this situation, I would be very grateful for the help. Thank you in advance! -
Optimize querysets calls when you need to get results separatelly for different attributes of a Model
I have a Model Account that can have multiple attributes. Based on attributes other queries are execute. To get an attribute I do a query: def get_context_data(self, **kwargs): accounts_h = Account.objects.filter(is_home=True) accounts_i = Account.objects.filter(is_featured=True) accounts_t = Account.objects.filter(is_t=True) products_h = Product.objects.filter(account_id__in=accounts_h) products_i = Product.objects.filter(account_id__in=accounts_i) companies_t = Company.objects.filter(account_id__in=accounts_t) The problem is that I have to do similar queries for multiple attributes(more than 6) on the Accounts, and other related Models which is not optimal. How can I optimize ? -
Why authenticate() return None for inactive users?
I have CustomUser like following : class CustomUser(AbstractBaseUser, PermissionsMixin): email = models.EmailField(max_length=100, unique=True) username = models.CharField(max_length=20, unique=True) is_active = models.BooleanField(default=False) is_staff = models.BooleanField(default=False) ... which is active default=False After user registration automatically handle UserLogin def which is : def UserLogin(request): if request.POST: username = request.POST['username'] user = authenticate(username=username, password=request.POST['password']) print('user :', user) # which is print None if user inactive if user is not None: print('is user active:', user.is_active) # should print True or False if user.is_active: login(request, user) ... else: # handle user inactive ... else: # for None user ... I still trying understanding why authenticate return None for inactive users ? After searching I found smilier issue user.is_authenticated always returns False for inactive users on template But didn't find an answer for my situation