Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Concurrency protection is not working
I go bananas here. With my attempts to implement concurrency protection. So I figured out there are 2 ways to do it. Optimistic - basically we add a version field to the record and each save will increase it. So if my current version field is different that one on the disc it means something got modified and I give an error. And the pessimistic approach that means we just lock a record and it will be not possible to edit. I implemented both ways plus concurrency package for Django and nothing works I teas on SQLLite and on Postgres with Heroku. Below is my view method it has both approaches for pessimistic, I lock with transaction atomic using select_for_update and for optimistic I use concurrency django package that increases my version field on each edit and do a simple comparison with on_disc value What I do wrong? Please help? @login_required def lease_edit(request,pk,uri): logger = logging.getLogger(__name__) title = 'Edit Lease' uri = _get_redirect_url(request, uri) with transaction.atomic(): post = get_object_or_404(Lease.objects.select_for_update(), pk=pk) if request.method == "POST": form = LeaseForm(request.POST, instance=post) if form.is_valid(): lease = form.save(commit=False) on_disc= Lease.objects.get(pk=post.id) if on_disc.version > post.version: messages.add_message(request, messages.ERROR, str(lease.id) + "-Error object was modified by another user. … -
Django serializer not save data to database but response is OK
The serializer below don't save changes to database but JSON response from API has new correct values! What is wrong with it? class FieldSerializer(serializers.ModelSerializer): class Meta: model = Field fields = 'id', 'name', 'default' class DocumentSerializer(serializers.HyperlinkedModelSerializer): field = FieldSerializer(many=False, read_only=True) def _save_field(self, instance): field = self.initial_data.pop('field', None) field_ids = field['id'] field = Field.objects.get(pk=field_ids) instance.field = field def save(self, **kwargs): instance = super().save(**kwargs) self._save_field(instance) -
Django query on related model
I have models like below class Scheduler(models.Model): id = <this is primary key> last_run = <referencing to id in RunLogs below> class RunLogs(models.Model): id = <primary key> scheduler = <referencing to id in Scheduler above> overall_status = <String> Only when the scheduler reaches the scheduled time of the job, RunLogs entry is created. Now I am querying on RunLogs to show running schedules as below. current = ResourceLog.objects\ .filter(Q(overall_status__in = ("RUNNING", "ON-HOLD", "QUEUED") | Q(scheduler__last_run__isnull)) The above query gives me all records with matching status from RunLogs but does not give me records from Scheduler with last_run is null. I understand why the query is behaving so but is there a way to get records from scheduler also with last_run is null ? -
What would be a good approach to construct docker containers for nginx, uwsgi, django
I have an approach that use a base OS image to construct nginx, uwsgi, django all inside a container for the purpose to fast deploy a website on a cloud service. And I also successfully building a reverse proxy to point to different django apps, but still inside one container. This approach has the drawback that, when I update one of the services or apps, I need to completely destroy the whole container and create a new container with all services. Therefore, I want to construct for nginx, uwsgi each with one container, for each django app a container. In short, I want to separate apps and services each with a container. Most of the tutorials online deploy such combinations inside one container. So my question is what would be the best approach to do so? For services such as nginx, uwsgi, should I construct them without a base OS image but simply just the service image, or I should construct them each with a base OS image and then add the service on top? Also, for my Django apps, should I construct for each app with a base OS image or just start base with python image? -
Django: apps.get_models() yields models from unittests
If I call this django method, in a test, it yields a lot of models which are not installed. These models are from other apps test code: apps.get_models() For example I get MROBase1 from the django package polymorphic test code. -
Ionic Framework Posting to Django Rest Framework Using HTTP Requests
I'm trying to create a new user in my Ionic app using Django as the backend. So far I can create a user no problem using Postman, but when I try to make an HTTP post request through my app I get the following error: {"password":["This field is required."],"username":["This field is required."]}. I am passing the username and password field to my Django app, but for some reason it doesn't register it. Is my post call wrong? DJANGO APP CODE serializers.py class UserSerializer(serializers.ModelSerializer): password = serializers.CharField(write_only=True) languages = serializers.ListField(child=serializers.CharField(max_length=30, allow_blank=True), source="userprofile.languages") class Meta: model = User fields = ('first_name', 'last_name', 'email', 'username', 'password', 'languages') def create(self, validated_data, instance=None): profile_data = validated_data.pop('userprofile') user = User.objects.create(**validated_data) user.set_password(validated_data['password']) user.save() UserProfile.objects.update_or_create(user=user, **profile_data) return user views.py @api_view(['POST']) @permission_classes((AllowAny,)) def create_user(request): serialized = UserSerializer(data=request.data) if serialized.is_valid(): serialized.save() return Response(serialized.data, status=status.HTTP_201_CREATED) else: return Response(serialized._errors, status=status.HTTP_400_BAD_REQUEST) IONIC APP CODE http.ts register(username, password, email, first_name, last_name, languages) { let url = "https://www.example.com/api/create_user/"; let headers = new Headers() headers.append("Content-Type", "application/x-www-form-urlencoded"); return this.http.post(url, {"first_name": first_name, "last_name": last_name, "email": email, "username": username, "password": password, "languages": languages }, {headers: headers}) .map(res => res.json()); } register.ts import { Component } from '@angular/core'; import { IonicPage, NavController, NavParams } from 'ionic-angular'; import { HttpProvider } … -
Django rest framework Cannot assign, must be a instance error for Mac
I have a one to one field on user model for birth record table. Done the api and it work perfectly in my Window 8.1 laptop. So i send it to my friend's laptop which is a Mac book, he make migration enter the details but he got this error instead. 1: ValueError: Cannot assign "1": "BirthRecord2.userId" must be a "MyUser" instance. 2: Cannot assign "1": "BirthRecord2.userId" must be a "MyUser" instance. In my laptop, the userId field in BirthRecord have a drop down to show the list of user. But in my friend's Macbook, it doesnt have the drop down of the existing user nor does it have the arrow down of the drop down at the side. This is how it shows in my laptop: https://imgur.com/a/n22DW Now i am unsure what is the problem as it works fine on my laptop even after dropping and recreating table. Or is it just MacBook problem ? Please help me Here's my code: models.py class MyUser(AbstractUser): userId = models.AutoField(primary_key=True) gender = models.CharField(max_length=6, blank=True, null=True) nric = models.CharField(max_length=9, blank=True, null=True) birthday = models.DateField(blank=True, null=True) birthTime = models.TimeField(blank=True, null=True) ethnicGroup = models.CharField(max_length=30, blank=True, null=True) mobileNo = models.IntegerField(blank=True, null=True) favoriteClinic = models.CharField(max_length=50, blank=True, null=True) … -
How to use Ssl over django-realtime
I have used the django-realtime for socket in django. But i have few problems to get the project live. How to use ssl over django-realtime? Is it necessary to run node node_modules/ishout.js/server.js over webhosting of django project? -
How to access a proxy class for Group from an user?
I have a Proxy for Group like that: from django.contrib.auth.models import Group class Role(Group): class Meta: proxy = True app_label = 'auth' @property def display_name(self): return self.name.title() And I want to access from an user, something like that with roles: my_user.groups.all() How can I access the roles from user? -
django UNIQUE constraint failed error
I have fallowing structure of database. I create ProductBidPrice class on view. Add all column has not have any problem but one column which is out_going_price and income_price. When I save the new ProductBidPrice django throw this error "UNIQUE constraint failed: sales_productbidprice.price_income_id" . I want use more than one to one realtionship. I can add and save Django Web Interface. But I can't add in the view. How can I fix this problem ? Sorry about my English. I hope explain my problem. models.py class ProductPriceHistory(BaseModel): currency = models.ForeignKey(PriceCurrency) price = models.FloatField() date = models.DateField() class Meta: abstract = True class ProductIncomePriceHistory(ProductPriceHistory): product = models.ForeignKey(Product, related_name="prices_income") def __str__(self): return "%s %s of %s" % (self.price, self.currency.name, self.product.name) class ProductOutgoingPriceHistory(ProductPriceHistory): product = models.ForeignKey(Product, related_name="prices_outgoing") def __str__(self): return "%s %s of %s" % (self.price, self.currency.name, self.product.name) class AbstractBidDirectSales(BaseModel): name = models.CharField(max_length=45) sales_date = models.DateField() customer = models.ForeignKey(Customer) class Meta: abstract = True class Bid(AbstractBidDirectSales): products = models.ManyToManyField(Product, related_name="bids", through="ProductBidPrice") def __str__(self): return "%s of %s" % (self.name, self.customer.name) class DirectSale(AbstractBidDirectSales): product = models.ManyToManyField(Product, related_name="directSales", through="ProductDirectSalesPrice") class Meta: verbose_name_plural = "DirectSales" def __str__(self): return "%s of %s" % (self.name, self.customer.name) class ProductDirectSalesPrice(BaseModel): product = models.ForeignKey(Product) directSales = models.ForeignKey(DirectSale) price_income = models.OneToOneField(ProductIncomePriceHistory) price_outgoing = … -
Django with ModWsgi and Apache not a valid application
So this is an odd problem - I'm trying to deploy Django to Apache, ModWSGI on a Mac running OSx but am running into the following error message: Target WSGI script '/Library/WebServer/local_biems/biems/wsgi.py' does not contain WSGI application Now: local_biems runs ok with python manage.py runserver with no silenced issues. So I believe my project is error free and ready for deployment. a test application local_blog runs ok with runserver AND with my virtual host configuration - so I'm assuming from this that Apache and MODWSGI are playing happily together. local_biems and local_blog are alongside each other in the /Library/WebServer/ and have identical permissions. If I update the file paths in the virtual host, restart apache and do a hard reload of the site I get the error above. WSGI files are identical. What can I try? I've tried the try/catch statement around get_wsgi_application() try: application = get_wsgi_application() print 'WSGI without exception' except Exception: print 'handling WSGI exception' # Error loading applications if 'mod_wsgi' in sys.modules: traceback.print_exc() os.kill(os.getpid(), signal.SIGINT) time.sleep(2.5) but same issue. -
django chat using socket.
I am trying to add chat function to my project follow django chat tutorial from this website https://blog.heroku.com/in_deep_with_django_channels_the_future_of_real_time_apps_in_django But, even if user type something, cannot see any chat. There is no error just doesn't work. I am not sure where should I fix to chat work well. Here's my codes. And if you can email and help me, I really appreciate. My email is bmj1219@gmail.com models.py class Room(models.Model): name = models.TextField() label = models.SlugField(unique=True) def __unicode__(self): return self.label class Message(models.Model): room = models.ForeignKey(Room, on_delete=models.CASCADE, related_name='messages') handle = models.TextField() message = models.TextField() timestamp = models.DateTimeField(default=timezone.now, db_index=True) def __unicode__(self): return '[{timestamp}] {handle} {message}'.format(**self.as_dict()) @property def formatted_timestamp(self): return self.timestamp.strftime('%b %-d %-I:%M %p') def as_dict(self): return {'handle': self.handle, 'message': self.message, 'timestamp': self.formatted_timestamp} view.py: def chat(request): return render(request, "prj/chat.html") def new_room(request): new_room = None while not new_room: with transaction.atomic(): l = Haikunator(adjectives=['chat']) label=l.haikunate() if Room.objects.filter(label=label).exists(): continue new_room = Room.objects.create(label=label) print("entered new_room", file=sys.stderr) return redirect(reverse('prj:chat_room', args=[label])) def chat_room(request, label): print("Why is this happening\n") room, created = Room.objects.get_or_create(label=label) messages = reversed(room.messages.order_by('-timestamp')[:50]) print("entered chat_room", file=sys.stderr) return render(request, "prj/room.html", { 'room': room, 'messages': messages, }) urls.py: app_name ='prj' urlpatterns = [ url(r'^$', views.IndexView.as_view(), name = 'index'), url(r'^prj/create_group/', views.group_create_view, name = 'create_group'), url(r'^prj/chat/', views.chat_view.as_view(), name = 'chat'), url(r'^new/$', views.new_room, name='new_room'), … -
Django - upload image file and store the image
In my custom user model, I need a field to store user's photo profile. So, I set a field photo_profile as an ImageField in the model. Now, if I go to my register page, there will be a button to upload image. After I choose my image, the of image is shown. However, when I click submit button, the webpage is asking "the field (the one for photo) is required". Is there an other way than using a FileUploadForm to solve this problem? Thanks in advance! -
Django CMS: Is there anything like "Custom Post Types" like WordPress?
I have a lot of knowledge to WordPress, but i am new to the Django CMS Framework. I've seen that i have a "Page" section in the top admin panel. Now i want to "duplicate" this "post type" (sorry for the WordPressish-language) to a new type called "Events". In WordPress, i would call register_post_type('events', $args), but how to do it in Django CMS? I know how to add model in my models.py file - but i want to access this new model separately in my admin bar. Are there any suggestions? Thank you in advance. -
Redirect and 'field' keyword issues when retriving objects from database
I have 3 models Account,Company, and Products. Company can have multiple products, Account can have multiple Companies. class Product(Meta): company = models.ForeignKey(Company, related_name='products', on_delete=models.CASCADE) class Company(Meta): account = models.ForeignKey(Account, related_name='account', on_delete=models.CASCADE) I'm using Django 2.0 new url patterns, and I defined the urls: path('dashboard/', include('accounts.urls', namespace='accounts')), in accounts urls.py path('companies/<int:pk>/', AccountCompanyDetailView.as_view(), name='detail_company'), In a CBV I'm trying to get a Product instance, if the Product doesn't exist, check if Company doesn't exist and base on the above results do a redirect. if not account: raise Http404 try: product = Product.objects.get(company__account=account, company__pk=company_pk, pk=product_pk) except Product.DoesNotExist: # try: # Company.objects.get(company__account=account, company__pk=company_pk) # except Company.DoesNotExist: # return redirect('accounts') return redirect('accounts:detail_company', pk=company_pk) return product If I use it as above (with Company code commented) when a product is wrong there is no error but redirect doesn't happen. If I un-comment the company part, I receive field error: Cannot resolve keyword 'company' into field. company is the ForeignKey on the Product Model to the Company Model. I'm doing the Company lookup after, and not before, Product lookup not to do two lookup(s) if is not necessary. -
Hosting Django Webserver on google Cloud VM
I've made a simple webserver and been running on local host but know want to transfer that to a vm. Whenever I run the command python manage.py runserver <"vm external ip address"> I receive the error code "Error: That IP address can't be assigned to" I'm extremely knew to web development and any instruction is greatly appreciated -
django chat using socket
I am trying to add chat function to my project follow django chat tutorial from this website https://blog.heroku.com/in_deep_with_django_channels_the_future_of_real_time_apps_in_django But, even if user type something, cannot see any chat. There is no error just doesn't work. I am not sure where should I fix to chat work well. models.py class Room(models.Model): name = models.TextField() label = models.SlugField(unique=True) def __unicode__(self): return self.label class Message(models.Model): room = models.ForeignKey(Room, on_delete=models.CASCADE, related_name='messages') handle = models.TextField() message = models.TextField() timestamp = models.DateTimeField(default=timezone.now, db_index=True) def __unicode__(self): return '[{timestamp}] {handle} {message}'.format(**self.as_dict()) @property def formatted_timestamp(self): return self.timestamp.strftime('%b %-d %-I:%M %p') def as_dict(self): return {'handle': self.handle, 'message': self.message, 'timestamp': self.formatted_timestamp} view.py: def chat(request): return render(request, "prj/chat.html") def new_room(request): new_room = None while not new_room: with transaction.atomic(): l = Haikunator(adjectives=['chat']) label=l.haikunate() if Room.objects.filter(label=label).exists(): continue new_room = Room.objects.create(label=label) print("entered new_room", file=sys.stderr) return redirect(reverse('prj:chat_room', args=[label])) def chat_room(request, label): print("Why is this happening\n") room, created = Room.objects.get_or_create(label=label) messages = reversed(room.messages.order_by('-timestamp')[:50]) print("entered chat_room", file=sys.stderr) return render(request, "prj/room.html", { 'room': room, 'messages': messages, }) urls.py: app_name ='prj' urlpatterns = [ url(r'^$', views.IndexView.as_view(), name = 'index'), url(r'^prj/create_group/', views.group_create_view, name = 'create_group'), url(r'^prj/chat/', views.chat_view.as_view(), name = 'chat'), url(r'^new/$', views.new_room, name='new_room'), url(r'^chat(?P<label>[\w-]{,50})/$', views.chat_room, name='chat_room'), ] chat.html: <p> <a class="button button-primary" href="{% url 'prj:new_room' %}">Create new chat room</a> </p> room.html: … -
Google App Engine serving 502s under light load
I have a Django rest framework based API hosted on google app engine with 1 instance using gunicorn. There is no scaling set up, yet. Here is the app.yaml : runtime: custom api_version: '1.0' env: flexible threadsafe: true env_variables: DEPLOYMENT_MODE: prod manual_scaling: instances: 1 The instance has 1 CPU and 1 GB of memory and usually serves 4-6 requests per second. The application is working fine, but sometimes under light load, I intermittently get 502s, for no apparent reason. Ignore the spikes on left and right, they are because of an actual heavy load that the instance could not handle. The Intermittent 502s are highlighted. I would like to understand the origin of these 502 errors. -
Check if there is someone logged in Django
I have a new django project I am working on. I am integrating Djangos user login and logout service that comes with the framework. I have a view and within the view, I want to check and see if there is a user object in the request.user. if there is not, I want to redirect to login page. If there is a user in the request.user, I want to display the users home page. how can I do this. Here is my code: def home(request): if not request.user: return redirect('login') else: User = request.user profile = Profile.objects.get(user = User) parameters = { 'user':User, 'profile':profile, } return render(request, 'user/home.html', parameters) It works if there is a user logged in but doesnt work if there is no user logged in... -
Pycharm/Django indentation error
I was asked in Pycharm some question along the lines of 'your code was was written with 4 spaces rather than tabs, press ok' but I cannot remember the exact wording. I didn't know what the option meant but since I pressed that button I'm getting an ident error. But I do not get an ident error in other locations. Now I'm getting an indentation error at 'list_display_links' and the code looks just the same as it does on this tutorial. from django.contrib import admin from .models import Post class PostModelAdmin(admin.ModelAdmin): list_display = ["title", "updated", "timestamp"] list_display_links = ['updated'] class Meta: model = Post tutorial image -
Django 1.8 querysets: how to compare date year to integer field?
I have a model with a DateField and a PositiveSmallIntegerField, is it possible to query for cases where date year is not the same as the integer one? Something like this that actually works: Expense.objects.exclude(date__year=F('year')) -
Python Django didnt save form to database
How i can save form to database with image, all works fine if i comment the line imagen = modelImageField so i think there is the problem, in model.py, all other part of form save to database if i comment the line, if i put the line on code no errors show, but not save a form to database too, can anyone help me with this? This is my View Views.py class donacion_Form(CreateView): template_name='App/donacion.html' model=donacion fields="__all__" success_url=reverse_lazy('mi_donacion') This is the form Forms.py class donacion_Form(forms.ModelForm): class Meta: model=donacion fields="__all__" This is the Model Model.py class donacion(models.Model): nombre=models.CharField(max_length=50) estados = ( ('EC', 'Excelente condicion'), ('BP', 'Buena presentacin'), ('PD', 'Presenta desgaste'), ('MD', 'Muy desgastada'), ) prendas = ( ('TP', 'Tops'), ('BT', 'Bottoms'), ('CZ', 'Calzado'), ('AS', 'Accesorios'), ('CM', 'Chamarras'), ) generos = ( ('MJR', 'Mujer'), ('HMB', 'Hombre'), ('UXA', 'Unisex adulto'), ('CHO', 'Chicos'), ('CHA', 'Chicas'), ('UXI', 'Unisex infantil'), ('BEB', 'bebes'), ) tallas = ( ('EC', 'XS'), ('CH', 'S'), ('MD', 'M'), ('GD', 'L'), ('EG', 'XL'), ('SG', 'XXL'), ) autor=models.CharField(max_length=25) estado = models.CharField( max_length=2, choices=estados, default='EC', ) genero = models.CharField( max_length=3, choices=generos, default='UXA', ) prenda = models.CharField( max_length=2, choices=prendas, default='TP', ) talla = models.CharField( max_length=2, choices=tallas, default='CH', ) direccion = models.CharField(max_length=500) /*if i comment this line imagen … -
Automatic drop down with models fields
I have a model : class Modelsname(models.Model): name = models.CharField(max_length=255) project = models.CharField(max_length=255) In the name field , i need the following fields . Instance-1: Display Name= instance1.COM Value=https//:website1.com Instance-2: Display Name=instance2.com Value=https://website2.com If user select the Instance-1 as drop down , follwoing should come as choices in project field . 1. IT - https://sasasa.com 2. POC - https://dsds.com 3. vDep - https://dsds.com 4. Tableau - https://sasssa.com if user select Instance-2 follwoing choices should come 1. Some2 Team - https://someteam.com/VSST How can i achive it , should i use pure django or javasript . Kindly help -
Move django-celery-monitor functionality to the site
How can i move django-celery-monitor functionality to the site-page? Main functions of this app are in admin-site, but i need this into my site. In the beginning, I tried to display the model on the site. But even this could not be done. # view.py from django_celery_monitor.models import TaskState class MonViewSet(ModelViewSet): model = TaskState list_display = ('task_id', 'state', 'name', 'args', 'kwargs', 'eta', 'runtime', 'worker') ordering = ('name',) filter_fields = ('name',) # url.py url('^mon/', include(views.MonViewSet().urls)), It raise the exception - namespace not register. Then i tried to add some string into my template, like this: <li><a href="{% url 'bgp_app:mon' %}">{% trans 'Monitor' %}</a></li> But this raise the exception to this string. I think, that there is more simple way to do what i need. I use Django 1.11, Celery Monitoring for Django 1.1.2. -
Django create list of items in multiple manytomany instances
I have a QuestionSet that is a manytomany of questions. Each QuestionSet has multiple questions associated with it. I want to get a list of all unique questions that are in two (or more) QuestionSets For example: First QuestionSet = Questions(1,2,3) Second QuestionSet = Questions(1,3,4) Output: List/Queryset/Something of Questions(1,2,3,4) models.py class QuestionSet(models.Model): name = models.CharField(max_length=255) questions = models.ManyToManyField(Question) class Question(models.Model): question_num = models.IntegerField(default=0,blank=False)