Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How is "self.argv = argv or sys.argv[:]" evaluated? [duplicate]
This question already has an answer here: Using “and” and “or” operator with Python strings 5 answers In django.core.management on row 133 there is a class defined with the following code: class ManagementUtility(object): """ Encapsulates the logic of the django-admin and manage.py utilities. """ def __init__(self, argv=None): self.argv = argv or sys.argv[:] self.prog_name = os.path.basename(self.argv[0]) self.settings_exception = None ...and so on. How can the variable self.argv be set to an expression which contains or? How is the statement self.argv = argv or sys.argv[:] evaluated? -
Django Models - Many to many persistent order
I'm looking for a way to have a Many-to-many relationship between objects while still persisting order. An example use case for this is a signup sheet. A user can sign up for many events, but I need to know who signed up first, second, third, etc... Is there a straight forward way to doing this? -
Picking second-tier foreign key from list in django form
I have an Entry model that is composed of (among other things) several FK relations to instances of model Pick. Pick consists of FK relations to model Car (this is for a race scoring web app) A rough schema: Entry | ---- Pick #class 1 | | | ----1st #(FK for instances of Car) | ----2nd | ----3rd | ---- Pick #class 2 | ----1st ----2nd ----3rd I can automatically create a form for Entry with ModelForm, but the form wants me to select populated entries for "Pick" from a list. Problem Form: Entry: Pick from list (class 1) [List of Pick objects] Pick from list (class 2) [List of Pick objects] Instead, I want to select the second-tier FKs in the Picks (the 1st, 2nd and 3rd places) in the form: Desired form: Entry: Class 1 1rd (Pick from list filtered for Class 1) 2rd (Pick from list filtered for Class 1) 3rd (Pick from list filtered for Class 1) Class 2 1rd (Pick from list filtered for Class 2) 2rd (Pick from list filtered for Class 2) 3rd (Pick from list filtered for Class 2) I have this working in Django, (and I understand how to filter for … -
How to edit an already saved form through views?
I'm using ajax to pass the uuid of an already saved form, I'd like to add some more values on one of the form's m2m field. So my question is how can I retrieve a form by it's uuid? Here's the views.py : def creationToEdit(request): if request.method == 'POST': form = UserInfoForm(request.POST) if form.is_valid(): for l in request.POST.getlist('layouts'): layouts = Layout.objects.filter(id=l) save_it.layout.add(layouts.first().id) ... How can I get back the form by it's uuid ? -
Django annotate and LEFT OUTER JOIN with desired WHERE Clause
Django 1.10.6 Asset.objects.annotate( coupon_saved=Count( Q(coupons__device_id='8ae83c6fa52765061360f5459025cb85e6dc8905') ) ).all().query produces the following query: SELECT "assets_asset"."id", "assets_asset"."title", "assets_asset"."description", "assets_asset"."created", "assets_asset"."modified", "assets_asset"."uid", "assets_asset"."org_id", "assets_asset"."subtitle", "assets_asset"."is_active", "assets_asset"."is_generic", "assets_asset"."file_standalone", "assets_asset"."file_ios", "assets_asset"."file_android", "assets_asset"."file_preview", "assets_asset"."json_metadata", "assets_asset"."file_icon", "assets_asset"."file_image", "assets_asset"."video_mobile", "assets_asset"."video_standalone", "assets_asset"."file_coupon", "assets_asset"."where_to_buy", COUNT("games_coupon"."device_id" = 8ae83c6fa52765061360f5459025cb85e6dc8905) AS "coupon_saved" FROM "assets_asset" LEFT OUTER JOIN "games_coupon" ON ("assets_asset"."id" = "games_coupon"."asset_id") GROUP BY "assets_asset"."id" I need to get that device_id=X into LEFT OUTER JOIN definition below. How to achieve? -
Django installation - Syntax error
After running below steps, # whoami root # echo $PYTHONPATH /usr/lib/python3.6/site-packages # # easy_install3 --install-dir /usr/lib/python3.6/site-packages django==1.9 Creating /usr/lib/python3.6/site-packages/site.py Searching for django==1.9 Reading https://pypi.python.org/simple/django/ Best match: Django 1.9 Downloading https://pypi.python.org/packages/c2/14/e282ae720c21b48316b66126d7295ace0790438b27482b7a3dd9a6e3c3e1/Django- 1.9.tar.gz#md5=110389cf89196334182295165852e082 Processing Django-1.9.tar.gz Writing /tmp/easy_install-5672_wl4/Django-1.9/setup.cfg Running Django-1.9/setup.py -q bdist_egg --dist-dir /tmp/easy_install-5672_wl4/Django-1.9/egg-dist-tmp-iuog46mc no previously-included directories found matching 'django/contrib/admin/bin' warning: no previously-included files matching '__pycache__' found under directory '*' File "build/bdist.linux-x86_64/egg/django/conf/app_template/models.py", line 1 {{ unicode_literals }}from django.db import models ^ SyntaxError: invalid syntax File "build/bdist.linux-x86_64/egg/django/conf/app_template/apps.py", line 4 class {{ camel_case_app_name }}Config(AppConfig): ^ SyntaxError: invalid syntax creating /usr/lib/python3.6/site-packages/Django-1.9-py3.5.egg Extracting Django-1.9-py3.5.egg to /usr/lib/python3.6/site-packages File "/usr/lib/python3.6/site-packages/Django-1.9-py3.5.egg/django/conf/app_template/models.py", line 1 {{ unicode_literals }}from django.db import models ^ SyntaxError: invalid syntax File "/usr/lib/python3.6/site-packages/Django-1.9-py3.5.egg/django/conf/app_template/apps.py", line 4 class {{ camel_case_app_name }}Config(AppConfig): ^ SyntaxError: invalid syntax Adding Django 1.9 to easy-install.pth file Installing django-admin.py script to /usr/lib/python3.6/site-packages Installing django-admin script to /usr/lib/python3.6/site-packages Installed /usr/lib/python3.6/site-packages/Django-1.9-py3.5.egg Processing dependencies for django==1.9 Finished processing dependencies for django==1.9 # I see syntax error in Django code, amidst installation. Question: Can this syntax error get ignored? -
Check whether an object with its unique together fields exist to create or delete before saving
Please consider this Ticket model, where its two fields (show and seat) should be unique together. Also it has a boolean field (paid) to indicate whether the ticket is paid or not. model: class Ticket(models.Model): show = models.ForeignKey(Show) seat = models.ForeignKey(Seat) user = models.ForeignKey(User) paid = models.BooleanField(default=False) class Meta: unique_together = ('show', 'seat') This is an example of the client side data {u'seat': 50, u'user': 3, u'show': 2} What I would like to do is check whether there is any Ticket with the provided data (seat and show). If there is no such Ticket then create a new one. Or else, if there is a Ticket, then check if that ticket has been paid. If its not paid then delete that ticket and create a new one with the new data, or else raise an error. I tried doing this way in the serializer, but I am still getting a uniqueness error: class TicketSerializer(serializers.ModelSerializer): class Meta: model = Ticket fields = '__all__' def validate(self, data): try: ticket = Ticket.objects.get(seat=data['seat'], show=data['show']) if not ticket.paid: ticket.delete() return data except Ticket.DoesNotExist: return data -
How to make multiple models(database in MYSQL) in python?
I need to make some more than 1000 (database(MYSQL)) models in Django with respective to project based on saving records for multiple time slot in each day within several different tables for almost 1 year. Since a single app in django allows single models.py file means single models / (database(MYSQL)). I tried a lot to make models without app but i am unable to do it. Please suggest me the solution? [Requirement Example]: Saving data of multiple meeting in time slot of multiple person for 1 year. I am making person_id as table. Or new suggestions are welcomed to make it done. -
save md5 password in md5 format django?
i am migrating my database and i have a user table which has password store in md5?So i want to store my password in md5 only and if user enter the password it accepts it.so is there any way i can save my password in md5. say for example my user has a password :-'e10adc3949ba59abbe56e057f20f883e' password =request.POST.get('password').strip() confirmPassword =request.POST.get('confirmPassword').strip() if password != confirmPassword: messages.error(request,'password and confim password must be same') return render(request, 'templates/sign-up.html') if User.objects.filter(email=email).exists(): messages.error(request, 'This email already exists') return render(request, 'templates/sign-up.html') new_password = make_password(password) staff = False superUser = False status = True authUser = User( password=new_password, username=email, email=email,is_active=status, is_staff=staff, is_superuser=superUser) authUser.save() and i want to save that in my auth_user table how can i do that. -
what does braces proceeded by a dollar sign in shell?
I am reading some shell scripts and try to understand it to make some small modification to it, but could not understand this: DEBUG="${DEBUG:False}" -
Why is the import statement importing a function outside of the class that is being imported?
I was under the understanding that using the syntax: from foo import y will import the class y from foo.py. If this is true how come when I use the following: models.py from django.db import models from .utils import codeGenerator, createShortcode class KirrUrlManager(models.Manager): def all(self, *args, **kwargs): qs_main = super(KirrUrlManager, self).all(*args, **kwargs) qs = qs_main.filter(active=True) return qs def refreshShortCodes(self): qs = KirrUrl.objects.filter(id__gte=1) #id_gte is primary key newCodes = 0 for q in qs: q.shortcode = createShortcode(q) q.save() newCodes +=1 return "new codes made: {i} ".format(i=newCodes) class KirrUrl(models.Model): url = models.CharField(max_length=220, unique=True) shortcode = models.CharField(max_length=50, unique=True, blank = True) timestamp = models.DateTimeField(auto_now=True,) timestamp = models.DateTimeField(auto_now_add=True,) active = models.BooleanField(default=True,) objects = KirrUrlManager() def save(self, *args, **kwargs): if self.shortcode is None or self.shortcode =="": self.shortcode = createShortcode(self) super(KirrUrl, self).save(*args, **kwargs) def __str__(self): return str(self.url) foo.py from django.core.management.base import BaseCommand, CommandError from shortener.models import KirrUrl class Command(BaseCommand): help = "refreshes all shortcodes" def handle(self, *args, **options): return KirrUrl.objects.refreshShortCodes() I am unsure why I am able to call the method "refreshShortCodes()" in foo.py. I am only using the import statement "from shortener.models import KirrUrl". Shouldnt this import statement only let me import the KirrUrl class? refreshShortCodes() is not part of the KirrUrl class, however it … -
django django-formtools formwizard inlineformsets filter
I'm in desperate need of help and unsure what to do. I'm using form-tools namedurlsessionwizardview. I'm using inlineformsets for step 4 but it is not filtering to what I have chosen on step 1. The inlineformset is outputting correctly however it is not filtering as I've said. I'm also using crispy forms which I think works really well Here my code MODELS.PY class ApplicationIndividualItems(models.Model): app_chosen_individual_id = models.AutoField(primary_key=True) application = models.ForeignKey('Application') product = models.CharField(max_length=50) category = models.CharField(max_length=50) group = models.CharField(max_length=50) item = models.CharField(max_length=50) FORMS.PY class CreateApplicationForm_Step4(forms.ModelForm): class Meta: model = models.ApplicationIndividualItems fields = '__all__' def __init__(self, *args, **kwargs): super(CreateApplicationForm_Step4, self).__init__(*args, **kwargs) self.helper = FormHelper() self.helper.form_tag = False self.helper.label_class = 'col-md-3' self.helper.field_class = 'col-md-9' self.helper.layout = Layout( Div( Fieldset( 'Please enter the individual module', Field('product',readonly=True), 'category', 'group', 'item', css_class="col-sm-12" ), ), ) VIEWS.PY def get_form(self, step=None, data=None, files=None): form = super(ApplicationWizard, self).get_form(step, data, files) if step is None: step = self.steps.current if step == "step4": prev_data = self.get_cleaned_data_for_step('step1') quantity = prev_data['no_modules_chosen'] product = prev_data.get('product','') print(product) formset = inlineformset_factory( models.Application, models.ApplicationIndividualItems, fields=("product","category","group","item"), extra=quantity, can_delete=False, form = forms.CreateApplicationForm_Step4, ) formset = formset( data, queryset = Product.objects.filter(product=product) ) return formset As you can see in my get forms function. I'm using the get_cleaned_data('step1) and then … -
Using databases with elastic beanstalk
I've been trying to deploy my Django based questionnaire application on AWS. I'm completely new to AWS and web apps for that matter. When I built my app it was running fine on localserver and I used this in my settings.py: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), } } I have managed to successfuly deploy my application using elastic beanstalk, and it was working fine. But then I had to make some changes in my code and i used 'eb deploy' from my local directory to deploy the new version. This lead to the loss of all the data(the responses filled till now). I realised I need to do something about my database. Since I'm completely new to all this, some help and guidance would be appreciated. -
Django multiple inline formset based in related Foreign Key existing registry
I need to generate to register a 'C' entry. Each 'C', needs to store a 'total' value by 'T' existent register. I need to generate a field for each 'T' object with field to 'total' value class C(models.Model): ubicacion = models.ForeignKey(Ubicacion) fecha = models.DateField() class T(models.Model): nombre = models.CharField(max_length=150) por_defecto = models.BooleanField('Mostrar por defecto', default=False) gravedad = models.CharField(max_length=10, choices=GRAVEDAD, blank=False) class A(models.Model): cierre = models.ForeignKey(C) tipologia = models.ForeignKey(T) total = models.IntegerField() This is my forms file class CForm(forms.ModelForm): class Meta: model = C fields = ['fecha', 'ubicacion'] class AInlineForm(forms.ModelForm): class Meta: model = A fields = ['tipologia', 'total'] widgets = { 'tipologia': forms.HiddenInput(), } AtencionesFormset = inlineformset_factory(C, A, form=AInlineForm) I need generate one inline form for each T register, and set 'tipologia' initial with the T value. Thx -
which database is better for my case? sql? nosql? newsql?
right now i have project which is about gathering information about country wide real estate active dealers and etc. the goal is to create an information system for real estate activists, the data gathering at the first stage would be with users input and at next stages we will use robots. at the end we will have an complete database to make advanced reports, even we have ideas about using AI technologies. we want to use python and Django, our big challenge in choosing right database management software are these issues: we may change or add new fields to classes, like id, postal code, etc. our goal is using this database to analyze and create advanced reports (maybe with machine learning and AI) can you help me with the right answer? thank you. -
Updating many objects with one form
I am building a shopping cart. I have a Product model and a ShoppingCartItem model: class Product(models.Model): name = models.CharField(max_length=64) description = models.TextField(blank=True) unit = models.CharField(max_length=16) price_per_unit = models.DecimalField(max_digits=11, decimal_places=2) image = StdImageField(default="default.jpg", variations={ 'thumbnail': {"width": 100, "height": 100, "crop": True} }) def __str__(self): return self.name class ShoppingCartItem(models.Model): user = models.ForeignKey(django_settings.AUTH_USER_MODEL, related_name='cart_items', on_delete=models.CASCADE) product = models.ForeignKey(Product, on_delete=models.CASCADE) quantity = models.PositiveIntegerField(default=1) # Update the quantity of an item in the shopping cart def update_quantity(self, quantity): if quantity <= 0: # If user sets quantity to 0 or less, delete the item. self.remove_item() else: self.quantity = quantity self.save() # Remove item from the shopping cart def remove_item(self): self.delete() def get_ext_total(self): return Decimal(self.product.price_per_unit * self.quantity) I want the UX to be able to update quantities via a text box for many ShoppingCartItems at a time. I've looked at formsets and inline formsets but they appear to be more suited to the creation of objects and ManyToMany relationships from within each object rather than updating many objects at one time. Below is an example of my shopping cart: What's the best way to go about doing this? -
how to send message from django server to a nodejs server and receive the reply?
Actually on the django server I have my website server running and on the nodejs server there is a bot which is running. I want my website to communicate with the bot forth and back. How can I achieve this? (for example: my bot accepts a trade given a list of items match to that trade and my website provides that list. So when I click a button my website will send the list to the bot and the bot will operate using that list) -
django SearchFilter is not filtering the list of queryset,it returns all of it
this is my view views.py file class StudentList(generics.ListAPIView): queryset = Student.objects.all() serializer_class = StudentSerializer #pagination_class = StudentPageNumberPagination filter_backends = [SearchFilter] search_fields=['name','mobile'] this is my serializers class class StudentSerializer(serializers.ModelSerializer): class Meta: model=Student fields=('id','name','mobile','time','late','date') this is what i type in browser http://192.168.0.118:8000/students/?name=ket and i get all of items in the database -
How to optimize/simplify heapsorting django objects? (can't use modules and db sorts)
I have to ask for some help with an assignment I got as a test for a django internship. I had to make and imaginary api with rabbits and their carrots. Each rabbit was supposed to have a number of carrots, but the api had to be designed to allow for easy addition of other kind of vegetable. I rejected integer field for each vegetable and instead went for vegetable object with type and value of vegetable. Problem is, the assignment also included listing the rabbits sorted by carrots, descending. They wanted me to implement heapsort, no database sort was allowed, no external libs. While i had no problem with that, I am having trouble with time constraints they thought of - for 20 000 rabbits to be sorted in under 30 seconds, ideally 5 seconds. And it already takes 5 seconds with 200 rabbits(just sorting and serializing to json). I make a queryset that has only rabbits with "carrots" vegetables. Then I force it into normal list and run heapsort function on it. How would I need to change it to be faster? Is it even possible? I will be very happy if someone helps even a bit. Thank … -
Run the right scripts before deployment elastic beanstalk
I am editing my .ebextensions .config file to run some initialisation commands before deployment. I thought this commands would be run in the same folder of the extracted .zip containing my app. But that's not the case. manage.py is in the root directory of my zip and if I do the commands: 00_activate: command: "source /opt/python/run/venv/bin/activate" 01_collectstatic: command: "python manage.py collectstatic --noinput" I get a ERROR: [Instance: i-085e84b9d1df851c9] Command failed on instance. Return code: 2 Output: python: can't open file 'manage.py': [Errno 2] No such file or directory. I could do command: "python /opt/python/current/opt/manage.py collectstatic --noinput" but that would run the manage.py that successfully was deployed previously instead of running the one that is being deployed atm. I tried to check what was the working directory of the commands ran by the .config by doing command: "pwd" and it seems that pwd is /opt/elasticbeanstalk/eb_infra which doesn't contain my app. So I probably need to change $PYTHONPATH to contain the right path, but I don't know which path is it. In this comment added the following to the .config file: option_settings: aws:elasticbeanstalk:application:environment: DJANGO_SETTINGS_MODULE: myapp.settings PYTHONPATH: "./src" Because his manage.py lives inside the src folder within the root of his zip. In … -
Unable to load Vue in a Django project
I'm currently working on a django(1.11) project and I'm also experimenting with VueJS for front-end, The VueJS does not load in the django framework but it does load when I use a regular HTML without making it a django template. I used the inspect element and found that the Sources are different on both the modes In the HTML (file:///home/pc/HTML%20and%20CSS/vuetrial.html) The source _vendor.js loads just fine. In the django project the Inspect element says Error loading this URL: Could not load the source for resource://gre/modules/ExtensionContent.jsm -> moz-extension://b3d4e690-c696-4958-b996-1a40eefba285/src/js/_vendor.js. out of memory Thank you in advance! -
Can't connect to Django sslserver with curl
I'm running a Django backend on my local machine with django-sslserver. When I run it with python manage.py runsslserver, I get this output: Validating models... System check identified no issues (0 silenced). July 01, 2017 - 15:02:32 Django version 1.11.2, using settings 'WallApp.settings' Starting development server at https://127.0.0.1:8000/ Using SSL certificate: /Users/mddrill/WallApp/venv/lib/python3.6/site-packages/sslserver/certs/development.crt Using SSL key: /Users/mddrill/WallApp/venv/lib/python3.6/site-packages/sslserver/certs/development.key Quit the server with CONTROL-C. When I try connecting to it with curl by using the ssl cert and key provided curl --cacert /Users/mddrill/WallApp/venv/lib/python3.6/site-packages/sslserver/certs/development.crt --key /Users/mddrill/WallApp/venv/lib/python3.6/site-packages/sslserver/certs/development.key https://127.0.0.1:8000/ It gives me this curl: (51) SSL: certificate verification failed (result: 5) I can connect to it just fine by disabling cert verification curl -k https://127.0.0.1:8000/ But I want to connect using the ssl certificate. Why is the ssl certificate provided by django-sslserver not working? -
Django models DateTimeField doesn't support microsecond
I am currently developing an application using already established databases system with mssql. Models were created using the inspect method : manage inspectdb I corrected the field guessed (floatfield), but I have a problem with DateTimeFields. In the database, DateTimeFields are precise up to microseconds and Django doesn't support this precision. Obtening the following error: Exception Type : AttributeError Exception Value : microsecond Keeping in mind that I can't modifie the database fields definition and I need to display dates in the application , how do I attribute those fields? models.py : class Table(models.Model): id = models.AutoField(db_column='Id', primary_key=True) dateheure = models.DateTimeField(db_column='DateHeure') code = models.CharField(db_column='Code',max_length=20) I tried all type of fields, but all give the same error. -
Django: Login_url differing depending on user properties
I have a view that has the following Auth Decorator: @user_passes_test(logged_in_check, login_url=if_admin, redirect_field_name = None) where I want the login_url to change depending on whether the user is an admin or not, so I created a method like so... def if_admin(request): if request.user.is_admin: return '/admin/' else: return '/' However this returns a NoReverseMatch error. How would I be able to achieve this? So if user is admin the login_url='/admin/', but if not then the login_url='/'? Thanks! Edit I should clarify but this decorator is for the login page view, so the logged_in_check parameter will check if the user is anonymous or not. If the user is logged in then they shouldn't be able to access the login view, and hence should be redirected by the 'login_url' as shown above. -
Thread safe append to a file from Django application without Celery
I have small Django application. During each request, I want to gather some request data (using custom middleware) and append it to a file. Since the application is running in multithreaded environment, I want the append to be thread safe. I have done some research, but most of the time people recommend celery. Since the application is small, I would like to avoid using celery or some form of a queue. I am ok with simple file locking, however, I do not know how to implement it with Django, where I do not manage the main thread directly. The only thing I have found is this Django's module, but it I am not sure if it solves my problem. Can I simply run that peace of code from my middleware? from django.core.files import locks with open('./file', 'wb') as f: locks.lock(f, locks.LOCK_EX) f.write('Django')