Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Should I use JSONField over ForeignKey to store data?
I'm facing a dilemma, I'm creating a new product and I would not like to mess up the way I organize my datas in my database from the start. I have two choices to organize my models, the first one would be to use foreign keys to link my models together. Class Page(models.Model): data = JsonField() Class Image(models.Model): page = models.ForeignKey(Page) data = JsonField() Class Video(models.Model): page = models.ForeignKey(Page) data = JsonField() etc... The second one is to keep everything in Page: Class Page(models.Model): data = JsonField() # videos and pictures, etc... are stored here Is one better than the other and why? This would be a huge help on the way I would organize my databases in the futur. -
Django 1.6.5 user registration error no such table: auth_user
my settings.py: INSTALLED_APPS = ( 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'crispy_forms', 'Mysite' ) AUTH_USER_MODEL = 'Mysite.PortalUserAbstract' my Mysite.models.py: class PortalUserAbstract(AbstractUser): is_client = models.BooleanField(default=False) is_manager = models.BooleanField(default=False) error message : OperationalError at /accounts/signup/client/ no such table: auth_user Request Method: POST Request URL: http://127.0.0.1:8000/accounts/signup/client/ Django Version: 1.6.5 Exception Type: OperationalError Exception Value: no such table: auth_user when i do manage.py syncdb it creates table "Mysite_portaluserabstract" but the auth module still looks for auth_user table. what am I missing? -
i am getting an error when running django
Unhandled exception in thread started by .wrapper at 0x038C1C48> this is what i get when trying to run an app that was created earlier on a different machine, when i create a new project it runs just fine but everytime i try to run the app that had been created before it throws the error listed here in above, please assist. this is the whole CMD dump: C:\Users\Gavina\Desktop\kesh\lawcases>python manage.py migrate Traceback (most recent call last): File "C:\Users\Gavina\AppData\Local\Programs\Python\Python37-32\lib\logging\config.py", line 562, in configure handler = self.configure_handler(handlers[name]) File "C:\Users\Gavina\AppData\Local\Programs\Python\Python37-32\lib\logging\config.py", line 735, in configure_handler result = factory(**kwargs) File "C:\Users\Gavina\AppData\Local\Programs\Python\Python37-32\lib\logging__init__.py", line 1092, in init StreamHandler.init(self, self._open()) File "C:\Users\Gavina\AppData\Local\Programs\Python\Python37-32\lib\logging__init__.py", line 1121, in _open return open(self.baseFilename, self.mode, encoding=self.encoding) FileNotFoundError: [Errno 2] No such file or directory: 'C:\opt\django-cases\logs\debug.log' The above exception was the direct cause of the following exception: Traceback (most recent call last): File "manage.py", line 10, in execute_from_command_line(sys.argv) File "C:\Users\Gavina\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django-2.1.3-py3.7.egg\django\core\management__init__.py", line 381, in execute_from_command_line utility.execute() File "C:\Users\Gavina\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django-2.1.3-py3.7.egg\django\core\management__init__.py", line 357, in execute django.setup() File "C:\Users\Gavina\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django-2.1.3-py3.7.egg\django__init__.py", line 19, in setup configure_logging(settings.LOGGING_CONFIG, settings.LOGGING) File "C:\Users\Gavina\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django-2.1.3-py3.7.egg\django\utils\log.py", line 76, in configure_logging logging_config_func(logging_settings) File "C:\Users\Gavina\AppData\Local\Programs\Python\Python37-32\lib\logging\config.py", line 799, in dictConfig dictConfigClass(config).configure() File "C:\Users\Gavina\AppData\Local\Programs\Python\Python37-32\lib\logging\config.py", line 570, in configure '%r' % name) from e ValueError: Unable to configure handler 'file' Thank you for your assistance -
Django cant translate captcha label
I'm using django-recaptcha and django-contact form. My contact form showing like this and working perfectly; It translates on all other titles except "Captcha". I could not find the word "Captcha" anywhere. i search this "Captcha" word all in my project but i cant find... No in my lang folder, no models or forms py How can i translate this label? where does this word come from? my contactform forms.py """ A base contact form for allowing users to send email messages through a web interface. """ from django import forms from django.conf import settings from django.contrib.sites.shortcuts import get_current_site from django.utils.translation import gettext_lazy as _ from django.core.mail import send_mail from django.template import loader class ContactForm(forms.Form): """ The base contact form class from which all contact form classes should inherit. """ name = forms.CharField(max_length=100, label=_('Your name')) email = forms.EmailField(max_length=200, label=_('Your email address')) title = forms.CharField(max_length=200, label=_('Subject')) body = forms.CharField(widget=forms.Textarea, label=_('Your message')) from_email = settings.DEFAULT_FROM_EMAIL recipient_list = [mail_tuple[1] for mail_tuple in settings.MANAGERS] subject_template_name = "contact_form/contact_form_subject.txt" template_name = 'contact_form/contact_form.txt' def __init__(self, data=None, files=None, request=None, recipient_list=None, *args, **kwargs): if request is None: raise TypeError("Keyword argument 'request' must be supplied") self.request = request if recipient_list is not None: self.recipient_list = recipient_list super(ContactForm, self).__init__(data=data, files=files, *args, **kwargs) … -
Django How To Query ManyToMany Relationship Where All Objects Match
I have the following models: ## Tags for issues class issueTags(models.Model): name = models.CharField(max_length=400) class issues(models.Model): tags = models.ManyToManyField(issueTags,blank = True) In my view I get an array from some client side JavaScript i.e. (Pdb) array_data = request.POST['arr'] (Pdb) array_data '["2","3"]' How should I filter my issues object to find all issues which match all tags in the array? (the 2,3 are the ID values for tag__id. If there is a better way to arrange the objects that would also work so I can search in this fashion. -
Django - modeling - multi-table reference
SOS - HELP : I am newbie in django ( I came from PHP (Laravel)): I need modeling the data : I have same models they are named Sources like(IOT, Sensosr, Totens, app etc..) each source has your particularity(conection params) and similarity, then I have scans, scans use sources information to execute (store information about execution) and produce activities on hosts. I need to link activities to sources through scans, so that, when a activity is showed, information about hosts, scans, and source are showed. I learning about abstract but it not so clear ! -
Best Way to set min/max values in Django Model field
I'm trying to get a field called WipID in my model to have the following: - Primary Key - and to have numbers between 000000001 and 999999999 Basically I want the field to always have 9 numbers. I don't care about auto-increment or not. I've tried a number variations, but right now I have this: WipID = models.BigAutoField(primary_key=True, validators=[MinValueValidator(000000001), MaxValueValidator(999999999)]) I've tried BigIntegerField and PositiveIntegerfield and those haven't worked either. What's the best way to accomplish this? Any help is greatly appreciated on this. -
django rest framework: how generate schema from serializer types?
I added the django-rest-swagger to my django-rest-framework project, following the instructions. The GUI looks fine, but the request description, which seems to be automatically generated from the APIViews get_serializer field has some issues. Specifically nested objects are ignored, and shows as {} all string types are just listed as string, ignoring the openapi format field So, for example, for this serializer class NestedSerializer(Serializer): firstname = StringField() class RequestSerializer(Serializer): name = NestedSerializer() date = DateField() choice = ChoiceField(['aa', 'bb', 'cc']) the GUI shows the request as name: {} date: string choice: string Am I missing something, or the project really doesn't support more specific types? -
Django project: within AJAX, parsererror SyntaxError: Unexpected end of JSON input
I am working on building a Django project. Once the button is clicked, the form will be submitted and some tasks will be performed based on the information from the form. However, in my case, the task can be done properly while there is always error pop up saying: "parsererror SyntaxError: Unexpected end of JSON input". Here is my AJAX function: $(document).on('submit', '#productForm', function(e){ e.preventDefault(); $.ajax({ method: 'POST', dataType: 'json', url: 'product/', data: { region: $("#Region-choice").val(), country: $("#Country-choice").val(), product: $("#Product-choice").val(), dvn: $("#dvn").val(), reship: $("#reshipCheckbox").val(), reshipId: $("#reshipTextfield").val(), validator: $("#Validator").val()} }) .done(function(){ alert("Product Created!"); }) .fail(function(req, textStatus, errorThrown) { alert("Something went wrong!:" + textStatus + ' ' + errorThrown ); }); alert("Submitted!"); }); -
Django 1.8 QuerySet: .extra syntax in Q object
I have several complex SQL Statements which are used to filter a django Queryset using .extra(). qs.extra(where=["my_jsonb_field-->'my_key'::text LIKE %s"], params=["myValue"]) Since these are queries on json fields, there is no possibility to get rid of these statements (at least not with django 1.8). Is it possible to use Q() objects with the .extra() syntax? # Q has no .extra Q().extra(...) # Q has no .raw Q().raw(...) -
AttributeError: 'function' object has no attribute 'get_extra_actions'
I defined this routing in my urls.py: from django.contrib import admin from django.urls import path from api import views from rest_framework import routers from django.conf.urls import url, include router = routers.SimpleRouter() router.register(r'country', views.get_country, base_name="Country") router.register(r'city', views.get_city, base_name="City") router.register(r'state', views.get_state, base_name="state") urlpatterns = [ path('admin/', admin.site.urls), url(r'^', include(router.urls)) ] But when I run it I get the following error: AttributeError: 'function' object has no attribute 'get_extra_actions' -
Category based list View in django
I have two model 1 is category, 2nd is details and I want make a view where i can click on a category and the link should take me to the list only for the current category what i clicked. my models are given: from django.db import models from django.utils import timezone from django.contrib.auth.models import User from django.urls import reverse class FoodCategory(models.Model): categoryname = models.CharField(max_length=100) categorydetails = models.CharField(max_length=1000) categoryimage = models.ImageField(default='cat_def.jpg', upload_to='catimg') class Meta: verbose_name = 'Food Category' def __str__(self): return self.categoryname class FoodDetails(models.Model): fromcategory = models.ForeignKey(FoodCategory, on_delete=models.CASCADE) foodname = models.CharField(max_length=100) fooddetails = models.CharField(max_length=1000) foodimage = models.ImageField(default='food_def.jpg', upload_to='fodimg') armodel = models.CharField(default='andy.sfb', max_length=50) additiondate = models.DateTimeField(default=timezone.now) addedby = models.ForeignKey(User, on_delete=models.CASCADE) class Meta: verbose_name = 'Food Detail' def __str__(self): return self.fromcategory.categoryname + \ ' - ' + self.foodname + \ ' - ' + 'added by' + \ ' - ' + self.addedby.username def get_absolute_url(self): return reverse('food-details', kwargs={'pk': self.pk}) -
Django with Peewee Connection Pooling MySQL disconnect
I'm running a Django project with Peewee in Python 3.6 and trying to track down what's wrong with the connection pooling. I keep getting the following error on the development server (for some reason I never experience this issue on my local machine): Lost connection to MySQL server during query The repro steps are reliable and are: Restart Apache on the instance. Go to my Django page and press a button which triggers a DB operation. Works fine. Wait exactly 10 minutes (I've tested enough to get the exact number). Press another button to trigger another DB operation. Get the lost connection error above. The code is structured such that I have all the DB operations inside an independent Python module which is imported into the Django module. In the main class constructor I'm setting up the DB as such: from playhouse.pool import PooledMySQLDatabase def __init__(self, host, database, user, password, stale_timeout=300): self.mysql_db = PooledMySQLDatabase(host=host, database=database, user=user, password=password) db_proxy.initialize(self.mysql_db) Every call which needs to make calls out to the DB are done like this: def get_user_by_id(self, user_id): db_proxy.connect(reuse_if_open=True) user = (User.get(User.user_id == user_id)) db_proxy.close() I looked at the wait_timeout value on the MySQL instance and its value is 3600 so that … -
I have two models and they are connected through ForiegnKey in my Django Project
#Models.py class Appname(models.Model): name=models.CharField(max_length=150,blank=False,null=False) def __str__(self): return self.name class placement(models.Model): user=models.ForeignKey(User,related_name='placeid', null=True, default=None,on_delete=models.CASCADE) name=models.ForeignKey(Appname,related_name='appname',null=True,default=None,on_delete=models.CASCADE,editable=False) ad_space=models.CharField(max_length=150,blank=False,null=False) PID_TYPE = ( ('FN','FORMAT_NATIVE'), ('FNB','FORMAT_NATIVE_BANNER'), ('FI','FORMAT_INTERSTITIAL'), ('FB','FORMAT_BANNER'), ('FMR','FORMAT_MEDIUM,RECT'), ('FRV','FORMAT_REWARDED_VIDEO'), ) format = models.CharField(max_length=3,choices = PID_TYPE,default = 'FN',blank=False, null=False) pid=models.CharField( max_length=50,default='',blank=False, null=False) cpm=models.IntegerField(default=0,blank=False, null=False) ADS_TYPE=( ('FB','FACEBOOK'), ('G','GOOGLE'), ) source=models.CharField(max_length=2,choices=ADS_TYPE,default='FB',blank=False, null=False) comments=models.TextField(default='',blank=False, null=False) objects=models.Manager() def __str__(self): return self.ad_space def get_absolute_url(self): return reverse("dashapp:view") Here is the Ques. I save my first model through form using generic view now i have used ForeignKey in my 2nd model . I want that when i fill my second Form the name variable gets autofill with the first model value . can i do that?? -
Django cms - Plugin in Plugin relation
i am using django cms 3.5.x. I try to create a new plugin that contains other plugins, but not over the "normal" way (allow_child=True). I would like to say PluginBox should contain two PluginText and a other plugin PluginContainer should contain 4 PluginText. I also want to render the first PluginText of box inside a div and the second one inside a span. For example: class Box(CMSPlugin): text1 = TextPlugin text2 = TextPlugin <div class="box"> <div> {% redner text1 } </div> <span> {% redner text2 } </span> </div> -
Google Calendar API using "events.update()" function doesn't send notification to the "attendees", after "import" of a calendar using iCalUID
FYI - old_event is a "service.events().get() response instance" captured from an event in a different mail address abc@gmail.com. new_event = old_event.copy() imported_event = new_service.events().import_(calendarId='primary',body=new_event).execute() updated_event_body = imported_event.copy() updated_event_body['summary'] = 'New Summary' updated_event = new_service.events().update(calendarId='primary', eventId=updated_event_body['id'], sendNotifications = True, body=updated_event_body).execute() -
Is it possible to disable the generation of related objects when deleting an object via Django admin?
I'm currently maintaining a legacy system while a new system is brought up. I noticed recently that I get a timeout when trying to delete certain objects from a specific model. I've tracked this down to being related to the following question which has an accepted answer: Django admin hangs (until timeout error) for a specific model when trying to edit/create The problem I'm having is that the objects that are related are not directly related from my model in question. For example I have the following models (generically named to remain vague due to IP at my company): ModelA which is the model I'm seeing the issue with when deleting from the Django Admin site ModelB which contains a ForeignKey field to ModelA ModelC which contains a ForeignKey field to ModelB ModelD which contains a ForeignKey field to ModelC ModelE which contains a ForeignKey field to ModelD Model details: ModelE can contain tens/hundreds/thousands of entries for any entry of ModelC. Additionally ModelC can contain tens/hundreds/thousands of entries for any entry of ModelB Currently when I try to delete ModelA Django attempts to generate all the associated objects all the way down to ModelE which is causing a timeout in … -
Wagtail: Filter Pages by a ForeignKey
Using Wagtail I want to get a QuerySet of Pages whose specific subclass have a certain ForeignKey to a Snippet. from django.db import models from wagtail.core.models import Page from wagtail.snippets.models import register_snippet @register_snippet class Organization(models.Model): name = models.CharField(max_length=255, blank=False) class ArticlePage(Page): organization = models.ForeignKey( 'Organization', null=True, blank=True, on_delete=models.SET_NULL, related_name='+' ) So, how would I get a QuerySet of all Pages whose associated ArticlePage has an Organisation with an id of 1? -
CSRF Failure On AJAX POST Request After Deploy Django Application With Nginx
I use Nginx and Gunicorn to deploy my Django blog on VPS. When i push some data to Django backend via Jquery AJAX, then i got 403 CSRF error. I googled a lot but still can't figure out how to fix this problem. I tried to deploy them on my local computer with same configuration files, and everything is okay. I've copied the AJAX sample code from Django document: // get csrftoken via JavaScript function getCookie(name) { let cookieValue = null if (document.cookie && document.cookie !== '') { let cookies = document.cookie.split(';') for (let i = 0; i < cookies.length; i++) { let cookie = jQuery.trim(cookies[i]) // Does this cookie string begin with the name we want? if (cookie.substring(0, name.length + 1) === (name + '=')) { cookieValue = decodeURIComponent(cookie.substring(name.length + 1)) break } } } return cookieValue } function csrfSafeMethod(method) { // these HTTP methods do not require CSRF protection return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method)) } $.ajaxSetup({ beforeSend: (xhr, settings) => { let $captchaMassage = $('#captcha-message') let csrftoken = getCookie('csrftoken') console.debug('csrftoken: ' + csrftoken) if (!csrfSafeMethod(settings.type) && !this.crossDomain) { xhr.setRequestHeader("X-CSRFToken", csrftoken) } if ($captchaMassage) { $captchaMassage.text('please wait...') } } }) and this is my AJAX: $.ajax({ async: true, method: 'POST', url: '{% … -
How to add and update data into foreign key field in django model
I have two models which is related to a forignkey. class BikeModel(models.Model): City = models.ForeignKey(CityForBike, on_delete=models.CASCADE) BikeModels = models.CharField(default='', max_length=50) Image = models.ImageField(upload_to='bike_images', blank=True, null=True, default='https://www.urbandrive.co.in/Admin/API/UploadedFiles/CarImage/44b150b3-f61a-41b5-afd8-34ded18fa980.png') class Meta: verbose_name_plural = 'BikeModels' def __str__(self): return self.BikeModels class CityForBike(models.Model): CityForCars = models.CharField(default="",max_length=50) class Meta: verbose_name_plural = 'CityForBikes' def __str__(self): return self.CityForCars and i want to insert data to BikeModel. but it gives me error. AssertionError: You cannot call `.save()` on a serializer with invalid data. I want to know how to insert data to forign key field. if request.method == 'POST': import pdb; pdb.set_trace() input_data = json.loads(request.read().decode('utf-8')) print(input_data) serializer = serializers.BikeModelSerializer(data=input_data) if serializer.is_valid(): serializer.save() return render(request, "bike_model_add.html", {'car_city': car_city}, status=200) And this is the data i am sending. {'City': 'testo', 'BikeModels': 'ds'} -
Set conditions to a field in Django Model
This is my Models: class UserModel(models.Model): name = models.CharField(max_length=200) role = models.CharField(max_length=200) class TestModel(models.Model): field1 = models.TextField() field2 = models.TextField() owner = models.ForeinkeyField(UserModel, on_delete=models.CASCADE) Let the role field can have values role1, role2, and role3 and I want to restrict the TestModel having owner with role=role3 -
django admin access rights: edit_user vs. assign access rights
In Django Admin: If you add the access right to "edit users" to a user this user can: edit any user's profile edit all access rights of the user (thus making this user de-facto a superuser) Is there a way to limit a user to only update another users personal information: email, first_name, last_name, etc? -
vuejs - without any node mentioned
I am working on Django (Python based Web Framework) project with Vue.js as my front-end choice. Almost all articles about Vuejs mention Node - at least to start development server. I am looking for some good read which talks only about Vue.js and architecture part of the application. How to and where to create those store, components, routes files? What should be ideal location/directory structure to start Vuejs - without bothering about Node part of it. thank you -
Django app not loading CSS background-image, but image loads with inline styling. Is there a fix for this?
As the title states. I've run into an interesting problem. This is related to css background images. I am loading the app names and their models in a sidebar menu, and for some reason the images just won't load. I added the images in the static folder for the app. The code in the css file is the following: /* App Buttons and Icons */ #servers_icon { background-image: url("/static/bootstrap_admin/img/icon_servers_copy.png") no-repeat; } #sensors_icon { background-image: url("/static/bootstrap_admin/img/icon_sensors_copy.png") no-repeat; } Note the path. For some reason, django is refusing the load these files. The css file is being loaded and actively used by the app. The ID names are correct. However, the images just will not load. However, if I put them inline in the HTML file: <li style="background-image: url('/static/bootstrap_admin/img/icon_{{ app.app_label }}_copy.png'); background-repeat: no-repeat;" {% if app.app_url == current_url %}class="active"{% endif %}> <a href="{{ app.app_url }}" class="section" title="Models in the {{ name }} application"> {{ app.name }} </a> </li> Then the images load. Note that the path is the same. {{app.app_label}} is part of the in-template for loop that populates the menu. The label name and file name matches. In fact, the file name was renamed to match the app label name. Anyway, … -
django selection field value
i have created a selection field in django model , but when i try to call onchange in html the ajax code is not working. here is the code.. when i click on the match_recipient in this form i need value on the ajax but now i didnt get the value . There is showing undefined value models.py type = ( ('catchall' , 'Catch All'), ('match_recipient','Match Recipient'), ('match_header','Match Header'), ) class Routes(models.Model): expression_type = models.CharField(max_length=10,choices=type,default='catchall') actions = models.CharField(max_length=100) recipient = models.CharField(max_length=50) header_name = models.CharField(max_length=50) header_value = models.CharField(max_length=50) priority = models.IntegerField() user = models.ForeignKey(User, on_delete=models.CASCADE) form.py type = ( ('catchall' , 'Catch All'), ('match_recipient','Match Recipient'), ('match_header','Match Header'), ) class RouteForm(forms.ModelForm): expression_type = forms.ChoiceField(choices=type,widget=forms.Select(), required=True) actions = forms.CharField(help_text='Required', widget=forms.TextInput(attrs={'placeholder': 'address@example.com'})) recipient = forms.CharField(widget=forms.TextInput(attrs={'placeholder': 'recipient@example.com'})) header_name = forms.CharField( widget=forms.TextInput(attrs={'placeholder': 'X-Header-Name'})) header_value = forms.CharField( widget=forms.TextInput(attrs={'placeholder': 'Header Value'})) priority = forms.IntegerField(initial=0) class Meta: model = Routes fields = ('expression_type','actions','recipient','header_name','header_value','priority',) template.html <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <script type="text/javascript"> $(document).ready(function() { $("#recipient").hide(); $("#header_name").hide(); $("#header_value").hide(); $("#expression_type").change(function() { alert("ededde"); var a = $(this.text()); console.log(a); alert(a); if($(this).val() == "match_recipient"){ $("#recipient").show(); }else if($(this).val() == "match_header"){ $("#header_name").show(); $("#header_value").show(); } }); }); </script> </head> <form action="{% url 'route' %}" method="POST"> {% csrf_token %} <div class="field has-addons"> <div class="form-group row" id="expression_type"> <label class="col-sm-2 col-form-label">Expression Type</label> <div class="col-sm-10"> …