Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django tests for zero downtime schema migrations
This question touches the subject of zero downtime schema migrations in Django (like this one perhaps). A two-way compatible schema migration deployment is usually as follows (correct me if this list is missing a step): Scale up old code. Create new schema change with all fields nullable. Deploy schema change. Create new code change that uses new fields. Deploy new code. Scale down old code. Optionally deploy new changes that make these fields non-nullable. However, I have not found any resources in the Django docs about testing steps 2, 3, and 4. Ideally, before makemigrations generates a migration file, a series of tests should pass to indicate that the current codebase can run before and after this migration is run. Question: is there already a built-in mechanism in Django, by which the two interleaved states ((old code, new schema), (new code, old schema)) during a hypothetical zero downtime forwards and backwards migration, can be tested? -
Per-user sessions in django
I've been playing with sessions in django, but I have a few questions: I do not really understand where they are useful. I mean, I thought I'd be able to store data for my users without having to create specific fields in my model. But, looks like the session only refers to the browser id (is that right?) the user is currently using, so once they enter from another place the sessions dict is blank again. In the docs of django, it says the data is stored in the server side to avoid security problems related to cookies, but again, as I have understood the data is only temporary, right? Is there any way to keep track (storing data) of the interaction of a specific user with my site with sessions? Or the sessions are not dessigned for that? When it comes to users, loging in just means assigning the session dict to the user hash, id... (previously created), right? Finally, if you could show me a practical and real use of sessions it would be great, bc the comments example in the docs doesn't seem useful, since once you re-enter the site the dict will be blank again. Thank … -
Favicon redirect in django 2.0
I'm trying to redirect the default browsers request of /favicon.ico to serve the picture from my static folder and I get a 404(server log screenshot). settings.py STATIC_URL = 'static/' STATIC_ROOT = os.path.join(BASE_DIR, "static") urls.py from django.contrib import admin from django.contrib.staticfiles.storage import staticfiles_storage from django.urls import include, path from django.views.generic.base import RedirectView urlpatterns = [ path('admin/', admin.site.urls), path( 'favicon.ico', RedirectView.as_view(url=staticfiles_storage.url('upload.ico')) ), path('', include('uploader.urls')) ] My directory structure: ../ ├ imguploader/ | ├ __init__.py | ├ settings.py | ├ urls.py | └ wsgi.py ├ static/ | ├ admin/ | └ upload.ico ├ manage.py |... -
Add button against each record on django admin change list page?
I want to add a button against each row on django admin change list page. When that button is clicked, i want to make entries in some database table(all this happens on the backend) and after that the button should be disabled on the same page against that row. How can i achieve this? I have searched a lot button there is no solution available. -
AttributeError: type object 'BaseCommand' has no attribute 'option_list'
Hello i am trying to create search app in My Django project using Haystack and Solr but i receive this error "AttributeError: type object 'BaseCommand' has no attribute 'option_list'" I am running this command : python manage.py rebuild_index I am using : Python 3.6.4 solr-4.10.4 haystack 2.4.0 Django 2.0 If the post isn't clear i am ready to explain it more See the error -
'overflow: scroll' not working in Safari (11.0.2) on MacBook (10.13.2 ) or any browser on iPhoneX (11.2.1)
On the webpage below if you select a barber it reveals a hidden 'div' (id="booking-right") containing an 'iframe' (class="iframe") with a booking page. We have set our CSS to allow the 'iframe' to scroll up and down within the hidden 'div' using 'overflow: scroll'. As you may be able to see, this works fine in Chrome on MacBook, but won't work in Safari on MacBook or on any browser on my iPhoneX. This is a real problem because it means clients won't be able to scroll down to select appointment times for our barbers. http://cuttersclub.webfactional.com/barbers/ Any help would be much appreciated! barbers.html: <div id="div"> <!-- acuity --> <div id="booking-div"> <div id="booking-left"></div> <div id="booking-right"> <a><img id="close-image" src="{% static "img/close-button.svg" %}" alt="My image"></a> {% for BarberProfile in queryset_list %} <iframe class="iframe" id="{{BarberProfile.id}}-iframe" src="" frameBorder="0"></iframe><script src="https://d3gxy7nm8y4yjr.cloudfront.net/js/embed.js" type="text/javascript"></script> {% endfor %} </div> </div> <!-- acuity --> <!-- profile --> {% for BarberProfile in queryset_list %} <a class="profile-div" id="{{BarberProfile.id}}" target="{{BarberProfile.booking_link}}" onClick="toggle_content(this.id)"> <div id="image" style="background-image: url({{BarberProfile.image.url}})"> <div id="image-structure"></div> </div> <h4 id="name"> {{BarberProfile.first_name}} </h4> <p id="bio"> {{BarberProfile.bio}} </p> <img id="experience-image" src="{% static "img/experience.svg" %}" alt=""><p id="experience">{{BarberProfile.years_of_experience}} experience</p> <img id="ideal-image" src="{% static "img/speciality.svg" %}" alt=""><p id="ideal">Ideal for {{BarberProfile.ideal_for}} </p> </a> {% endfor %} <!-- profile --> </div> barbers.css: … -
Not found: /accounts/facebook/login in django allauth
What I am trying to do ? I am trying to login the user using their social account and I am doing this with the help of Django allauth. What is the problem ? My project works fine on my laptop (which is broken now) but I don't know why it doesn't work on my desktop. I get the following error on the console whenever I try to login using a social account: Error: Not Found: /accounts/facebook/login My Code: settings.py: DEBUG = True INSTALLED_APPS = [ ... 'django.contrib.auth', 'django.contrib.sites', 'allauth', 'allauth.account', 'allauth.socialaccount', 'allauth.socialaccount.providers.facebook' ] LOGIN_URL = 'login_url' LOGOUT_URL = 'logout_url' LOGIN_REDIRECT_URL = 'redirect_url' SITE_ID = 1 AUTHENTICATION_BACKENDS = [ 'allauth.account.auth_backends.AuthenticationBackend', 'Authentication.backends.EmailBackend', ] SOCIALACCOUNT_QUERY_EMAIL = True SOCIALACCOUNT_EMAIL_VERIFICATION = True SOCIALACCOUNT_EMAIL_REQUIRED = True TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(SETTINGS_PATH, 'templates')], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ ... 'django.template.context_processors.request' ], }, }, ] html: <div class="modal" id="loginModal" data-backdrop="static" data-keyboard="false"> <div class="modal-dialog"> <div class="modal-content"> <div class="modal-header"> <button class="close">&times;</button> </div> <form id='loginForm'>{% csrf_token %} <div class="modal-body"> <div class="col-xs-12"> <a href="/accounts/facebook/login"> Facebook </a> </div> </div> <div class="modal-footer"> <button type="submit" class="btn btn-default" id="login"> Login </button> </div> </form> </div> </div> </div> urls.py: urlpatterns = [ url(r'^accounts/', include('allauth.urls')), ... ] And have perfectly setup the social application … -
NoReverseMatch error during url
New to Django framework. Mostly reading through documentations. But this one i am unable to crack. Trying to add a URL to an headline, that will be forwarded to the 'headlines' post. The Error: NoReverseMatch at / Reverse for 'assignment_detail' with arguments '('',)' not found. 1 pattern(s) tried: ['assignment_detail/'] Request Method: GET Request URL: http://127.0.0.1:8000/ Django Version: 2.0.2 Exception Type: NoReverseMatch Exception Value: Reverse for 'assignment_detail' with arguments '('',)' not found. 1 pattern(s) tried: ['assignment_detail/'] Exception Location: C:\Users\internit\Dropbox\Python\codepython\env\lib\site-packages\django\urls\resolvers.py in _reverse_with_prefix, line 632 Python Executable: C:\Users\internit\Dropbox\Python\codepython\env\Scripts\python.exe Python Version: 3.6.2 Python Path: ['C:\Users\internit\Dropbox\Python\codepython\codepython', 'C:\Users\internit\Dropbox\Python\codepython\env\Scripts\python36.zip', 'C:\Users\internit\Dropbox\Python\codepython\env\DLLs', 'C:\Users\internit\Dropbox\Python\codepython\env\lib', 'C:\Users\internit\Dropbox\Python\codepython\env\Scripts', 'c:\program files (x86)\python36-32\Lib', 'c:\program files (x86)\python36-32\DLLs', 'C:\Users\internit\Dropbox\Python\codepython\env', 'C:\Users\internit\Dropbox\Python\codepython\env\lib\site-packages'] Server time: Thu, 8 Feb 2018 14:53:07 +0000 Error during template rendering In template C:\Users\internit\Dropbox\Python\codepython\codepython\codepython\templates\base.html, error at line 0 Reverse for 'assignment_detail' with arguments '('',)' not found. 1 pattern(s) tried: ['assignment_detail/'] 1 {% load static %} 2 3 4 5 6 7 8 9 10 CODEPYTHON.NET Traceback Switch to copy-and-paste view C:\Users\internit\Dropbox\Python\codepython\env\lib\site-packages\django\core\handlers\exception.py in inner response = get_response(request) ... ▶ Local vars C:\Users\internit\Dropbox\Python\codepython\env\lib\site-packages\django\core\handlers\base.py in _get_response response = self.process_exception_by_middleware(e, request) ... ▶ Local vars C:\Users\internit\Dropbox\Python\codepython\env\lib\site-packages\django\core\handlers\base.py in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) ... ▶ Local vars C:\Users\internit\Dropbox\Python\codepython\codepython\home\views.py in home return render(request, 'home.html', {'post':post}) ... ▶ Local vars home/urls.py from … -
FieldDoesNotExist: product_purchase_categories has no field named 'None' ManyToMany
I am trying to add ManyToMany relationships to an instance in and Django continues to throw a strange error. I am hoping someone has seen this before or may have some insight into why I am seeing this. Below are the two models I am working with. My product model is quite large so I slimmed it down. The other fields should not have any relevance. class baseModel(models.Model): created_date = models.DateTimeField(auto_now_add=True,blank=True) updated_date = models.DateTimeField(auto_now=True,blank=True) inactive = models.BooleanField(default = False,blank=True) class Meta: abstract = True class category(baseModel): name = models.CharField(max_length=255, help_text="",blank=True) short_name = models.CharField(max_length=255, help_text="",blank=True) external_id = models.IntegerField(help_text="",blank=True,null=True) sales_channel = models.ForeignKey('sales_channel',related_name = 'sales_categories',null=True,blank=True,on_delete=models.SET_NULL) purchase_channel = models.ForeignKey('purchase_channel',related_name = 'purchase_categories',null=True,blank=True,on_delete=models.SET_NULL) parent_category = models.ForeignKey('self',related_name='child_categories',null=True,blank=True,on_delete=models.SET_NULL) category_level = models.IntegerField(null=True,blank=True) def _product_count(self): "Number of Products" product_count = self.category_products.count() return product_count product_count = property(_product_count) def __str__(self): return self.name# + ' ('+str(self.product_count)+')' class product(baseModel): title = models.CharField(max_length=255, help_text="The title of the product.") additional_details = models.CharField(max_length=255, help_text="Additional product information provided by the supplier",null=True,blank=True,) description = models.TextField(max_length=4000, help_text="") # ... purchase_channel = models.ForeignKey('purchase_channel',related_name = 'products',null=True,blank=True,on_delete=models.SET_NULL) purchase_external_id = models.IntegerField(help_text="external_id from purchasing channel",null=True,blank=True) purchase_cost = models.DecimalField(max_digits=9,decimal_places=2, help_text="pruchase cost of the product.", blank=True, null=True) purchase_categories = models.ManyToManyField(category,related_name = 'categories_products',blank=True) # ... def __str__(self): return self.title Below is what I ran in shell. Grabbed a … -
django admin static isn't working
I'm trying to deploy my website on pythonanywhere and everything is working fine except of django admin. It's not showing css (staticfiles). Here is my static settings (I'm using django 1.8): STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles') STATIC_URL = '/static/' STATICFILES_DIRS = ( os.path.join(BASE_DIR, 'static'), ) On pythonanywhere, in static files section I've added: Url: /static/ Directory: /home/erebbit/hypercube/static I've also added this at the end of my urls.py: if True: urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) does anyone know what am I doing wrong? -
Azure event hubs python library
I'm trying to get the Azure event hubs python module to work. I've followed the instructions in the readme; which is mostly just "install Proto-c". Everything installs without any problems but when I try to run the receiver I get this: Traceback (most recent call last): File "recv.py", line 16, in from eventhubs import EventHubClient, Receiver, Offset File "/home/garr/Workspace/Bodaytrak/webhost/azure-event-hubs/eventhubs/init.py", line 23, in from proton import DELEGATED, Url, timestamp, generate_uuid, utf82unicode ImportError: No module named proton Anyone got any ideas? -
Django files storage: How to get base url of media file?
I'm using gcloud wrapped into django-storages logic. I have never feed the service with a url path of my bucket: only provided DEFAULT_FILE_STORAGE and GS_BUCKET_NAME which are the name of my glcoud project and storage. My question is: How can I get the full url of my images? My images are saved with a relative url, which make sens into the DB. But I can't found any right documentation about how you can get the base url of the django.core.files.storage collection of object storage. Some filestorage objects ask a valid relative image url in order to retrieve the full path. But this is not what I want: I just want to know (programatically) the base url of my (only one) bucket. The template {% image item.image %} is able to generate the full url, but from the code side view it seems totally obscure for me. Any help or advice? -
Django Modeltranslation: TranslationAdmin class does not copy the correct widget
I`m using a custom form for a django admin model with translated fields. But the widget of the form is not used. My code: models.py class Fact(models.Model): heading = models.CharField(max_length=200) translation.py class FactTranslationOptions(TranslationOptions): fields = ('heading') translator.register(Fact, FactTranslationOptions) admin.py class FactForm(forms.ModelForm): class Meta: model = Fact widgets = { 'heading': forms.Textarea } class FactAdmin(translationadmin.TranslationAdmin): form = FactForm admin.site.register(Fact, FactAdmin) With this code, the field heading does not show up as textarea. It`s a default input field. When I change FactForm to: class FactForm(ProductDataInlineFormBase): class Meta: model = Fact widgets = { 'heading_de': forms.Textarea, 'heading_en': forms.Textarea } the textarea widget is used. Am I doing something wrong, or is this a bug in django modeltranslation? -
Django CBV - set form class based on permissions?
I have created two forms in forms.py one form has less fields than the other. what I would like to now do is get the current users permissions and set the form class of the CBV based on those perms. below is my current view: class EditCircuit(UpdateView): model = Circuits # if user_passes_test(lambda u: u.has_perm('config.edit_circuit'))) form_class = CircuitForm # else # form_class = CircuitFormRestricted template_name = "sites/circuit_form.html" @method_decorator(user_passes_test(lambda u: u.has_perm('config.edit_circuit'))) def dispatch(self, *args, **kwargs): self.site_id = self.kwargs['site_id'] self.site = get_object_or_404(SiteData, pk=self.site_id) return super(EditCircuit, self).dispatch(*args, **kwargs) def get_success_url(self, **kwargs): return reverse_lazy("sites:site_detail_circuits", args=(self.site_id,)) def form_valid(self, form): form.instance.site_data = self.object.site_data return super(EditCircuit, self).form_valid(form) def get_form_kwargs(self, *args, **kwargs): kwargs = super().get_form_kwargs() return kwargs def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['SiteID']=self.site_id context['SiteName']=self.site.location context['FormType']='Edit' context['active_circuits']='class="active"' return context -
Authenticating Swagger API docs (drf-yasg)
I've setup DRF-YASG but am unable to figure out how to configure it to show Views that require Authentication. Below is the configuration. schema_view = get_schema_view( openapi.Info( title="Swagger Doc", default_version='v1', description="Test description", terms_of_service="https://www.google.com/policies/terms/", contact=openapi.Contact(email="contact@snippets.local"), license=openapi.License(name="BSD License"), ), validators=['flex', 'ssv'], permission_classes=(permissions.AllowAny,), # If I change the permission it throws an exception. See below public=False, patterns=public_apis, ) the public_apis are the APIs that I want a person to see after they have authenticated themselves. With the above configuration, it does not show a single API. It only shows the Authorize Button and text that says No operations defined in spec!. But if I change public=False to public=True then it shows all the APIs. PS: Earlier I was using Django Rest Swagger and I had been able to configure it to show the APIs only after the JWT token had been provided. Am is using JWT for authentication. Exception on Permission Change: Another issue is that if I change the permission above to a DRF Permission class the rendering fails with the error below: Internal Server Error: /swagger/ Traceback (most recent call last): File "/usr/local/lib/python3.6/site-packages/django/core/handlers/exception.py", line 41, in inner response = get_response(request) File "/usr/local/lib/python3.6/site-packages/django/core/handlers/base.py", line 217, in _get_response response = self.process_exception_by_middleware(e, request) File … -
Allowing user to register only if field information matches the one from database in Django
I am trying to allow a student user to register in the system only if the student_ID matches the one from database. But I don't know how to do it right. class StudentData(models.Model): name = models.CharField(max_length=30) surname = models.CharField(max_length=50) student_ID = models.CharField(unique=True, max_length=14) class StudentForm(forms.ModelForm): email = forms.EmailField(required=True) name = forms.CharField(max_length=50, required=True) surname = forms.CharField(max_length=50, required=True) student_ID = forms.CharField(required=True, max_length=14, min_length=14) student_data = StudentData.objects.all().values('student_ID') if form2.is_valid(): cd2 = form2.cleaned_data phone = cd2['phone'] for data in student_data: if data == 'student_ID': student_id = cd2['student_ID'] -
Django test post in localhost AttributeError
I have a test.py file that is supposed to send a POST request to my LocalHost site (if LH doesn't work for this I can also do test on test.domain.com). However, I am not getting any new information saved in my DB. I have tried this out with GET before and it worked perfectly. Error message in CMD: File "C:\Users\winkl\Desktop\VE\mysite\payment\views.py", line 36, in webhook user = User.objects.POST(id=request.POST('clientAccnum')) AttributeError: 'UserManager' object has no attribute 'POST' views.py @csrf_exempt def webhook(request): template_name = 'payment/index.html' hook = Webhook() #ERROR MESSAGE FOR LINE BELOW user = User.objects.POST(id=request.POST('clientAccnum')) hook.user = user hook.clientSubacc = request.POST('clientSubacc') hook.eventType = request.POST('eventType') hook.eventGroupType = request.POST('eventGroupType') hook.subscriptionId = request.POST('subscriptionId') hook.timestamp = request.POST('timestamp') hook.timestamplocal = timezone.now() hook.save() user = User.objects.POST(id=request.POST('clientAccnum')) hook.user = user hook.user.profile.account_paid = hook.eventType == 'RenewalSuccess' hook.user.profile.save() print (hook.user, hook.clientSubacc, hook.timestamplocal) return render(request, template_name) tests.py from django.test import TestCase import requests import json url = 'http://127.0.0.1:8000/payment/webhook/' data = {'user':'11', 'clientSubacc': '1111', 'eventType': 'RenewalSuccess', 'eventGroupType': 'Success', 'subscriptionId': '12345'} r = requests.post(url, (data)) Goal is to have this test post create a successful webhook which will be saved in my DB. This information updates my users account status. -
Tell what model a queryset is from in the template
I am creating a list containing items from two different models and passing it to my template. Here is my view function: def newsfeed(request): Text = Post.objects.all().order_by('-Timestamp') Images = ImagePost.objects.all().order_by('-Timestamp') Posts = [] while True: if Text[0].Timestamp >= Images[0].Timestamp: Posts.append(Post.objects.get(id=Text[0].id)) Text = Text.exclude(id=Text[0].id) else: Posts.append(ImagePost.objects.get(id=Images[0].id)) Images = Images.exclude(id=Images[0].id) if len(Text) == 0: for i in Images: Posts.append(i) break elif len(Images) == 0: for i in Text: Posts.append(i) break print(Posts[:6]) return render(request, 'campaign/newsfeed.html', { "posts": Posts, }) I need a way to find out which model each item in the list was from in the template so that I know how to render the item. Is there a way to tell without sending further data to the template? -
Django is not available from forwarded port
I'm trying to connect to my website from another node on another network. If the nodes are in the same network, i can connect to the website without a problem. I've forwarded port for ssh and Django (8000), I also have apache ready on port 9080. ssh and apache ports work fine when connecting to them from external ip address, Django does not for some reason. First, i tried to run the server on port 8000: python manage.py runserver 0.0.0.0:8000 This works completely fine when connecting from the node that is in the same network as the server, but for some reason, whenever i try to access it from external ip address, the connection is refused. To make sure it was Django, I also tried running the server on the same port as Apache (9080), although, i didn't expect "errorless" response, since i knew that port was occupied. But there was no change at all, I was still getting the same Apache page that i would get before. It seems like Django has no effect for external connections, what could be the reason? I also struggle to understand the purpose of other http web server platforms in this case (e.g … -
CSV import into empty Django database with foreign key field
I'm a little new to this, and figuring it out as I go. So far so good, however I have having trouble importing a field that has a foreign key. I have about 10,000 rows in a csv file that I want to add to the database. As you can imagine, entering 10,000 items at a time is too labour intensive. When I try for an import I get this error: ValueError: invalid literal for int() with base 10 This is because (i think) it is trying to match the related model with the id. However the database is empty, so there is no id, and furthermore, the "author" field in my csv (the one with the foreign key) doesn't have an id yet. ( i assume this is created when the record is). Any suggestions? Sorry in advance for the newbie question. -
How can I access request object in the wagtail Page model?
I wanna dynamically set default value of the field to the currently logged in user: class SimplePage(Page): author = models.CharField(max_length=255, default=request.user) I know about get_context, but class attributes cannot call instance methods. def get_context(self, request, *args, **kwargs): return { PAGE_TEMPLATE_VAR: self, 'self': self, 'request': request, } Any more ideas? Essentially whoever is logged in into the admin should be added to the author field. -
Django Image kit/boto/django-stroages - s3 forbidden for ImageKit files
im using s3 as my backend for media files and am receiving the below error, Im not sure I this an issue with imagekti, boto, or Django storages? I am running the below versions: boto==2.48.0 boto3==1.5.22 botocore==1.8.36 django-storages==1.6.5 django-imagekit==4.0.2 pilkit==2.0 Pillow==5.0.0 im not sure how to troubleshoot this as im not sure which component could be failing? this is in my dev env, my live envoirment works and is using the following versions: boto==2.48.0 boto3==1.4.7 botocore==1.7.35 django-storages==1.6.5 django-imagekit==4.0.1 pilkit==2.0 Pillow==4.3.0 settings.py AWS_ACCESS_KEY_ID = os.environ['AWS_LIVE_KEY_ID'] AWS_SECRET_ACCESS_KEY = os.environ['AWS_LIVE_KEY_PASS'] AWS_DEFAULT_ACL = 'private' # Tell django-storages that when coming up with the URL for an item in S3 storage, keep # it simple - just use this domain plus the path. (If this isn't set, things get complicated). # This controls how the `static` template tag from `staticfiles` gets expanded, if you're using it. # We also use it in the next setting. AWS_S3_CUSTOM_DOMAIN = '%s.s3.amazonaws.com' % AWS_STORAGE_BUCKET_NAME STATICFILES_LOCATION = 'static' STATICFILES_STORAGE = 'itapp.functions.StaticStorage' STATIC_URL = "https://%s/%s/" % (AWS_S3_CUSTOM_DOMAIN, STATICFILES_LOCATION) MEDIAFILES_LOCATION = 'media' MEDIA_URL = "https://%s/%s/" % (AWS_S3_CUSTOM_DOMAIN, MEDIAFILES_LOCATION) DEFAULT_FILE_STORAGE = 'itapp.functions.MediaStorage' DOCUMENT_ROOT = '/documents/' LOGIN_REDIRECT_URL = '/' LOGIN_URL = '/login/' THUMBNAIL_ALIASES = { '': { 'thumb': {'size': (200, 150), 'crop': True}, }, … -
Django 2.0 Static Files not recognized in Apache2
My website is online, but it can't find the static files ;/ The configurations seem to be all ok, can't find the error... I don't have admin permission on the server, so it kind'a sucks.. but, at least they pass me the configurations they've put.. Apache Configuration: <VirtualHost *> ServerAdmin suporte@pop-rs.rnp.br DocumentRoot /home/metis/public_html/ ServerName agata.pgie.ufrgs.br ServerAlias www.agata.pgie.ufrgs.br #ErrorLog /var/log/apache2/agata-error.log #CustomLog /var/log/apache2/agata-access.log common <Directory /home/metis/public_html/static> Require all granted </Directory> <Directory /home/metis/public_html/AGATA/textMiningProject> <Files wsgi.py> Require all granted </Files> </Directory> WSGIDaemonProcess agata python-path=/home/metis/public_html/AGATA python-home=/home/metis/public_html/AGATA/agataenv WSGIProcessGroup agata WSGIScriptAlias / /home/metis/public_html/AGATA/textMiningProject/wsgi.py </VirtualHost> Django Version: 2.0 settings.py Static files (CSS, JavaScript, Images) https://docs.djangoproject.com/en/1.11/howto/static-files/ STATIC_PATH = os.path.join(BASE_DIR,'static') STATIC_URL = '/static/' # You may find this is already defined as such. STATIC_ROOT = '/home/metis/public_html/static' STATICFILES_DIRS = [ STATIC_PATH ] MEDIA_ROOT = os.path.join(BASE_DIR, 'media') MEDIA_URL = '/media/' And it was asked to the admins to insert the following, no changes in the result tho.. Alias /media/ /products/static Alias /static/ /products/static <Directory /products/static> Order allow,deny Allow from all </Directory> can someone help? -
Django: How do I do order_by for this model and is all() efficient for this query?
New to Django. I have these models: class ClinicDoctor(models.Model): doctor = models.ForeignKey('User', related_name='doctorsF') clinic = models.ForeignKey(Clinic, related_name='clinicsF') class Day(models.Model): day = models.CharField(max_length=20) class Shift(models.Model): shift = models.CharField(max_length=20) days = models.ManyToManyField(Day, through='DayShift', related_name='to_day_shift') class DayShift(models.Model): time = models.TimeField() day = models.ForeignKey(Day, related_name='to_day') shift = models.ForeignKey(Shift, related_name='to_shift') clinics_doctors = models.ManyToManyField(ClinicDoctor, through='ClinicDoctorDayShift', related_name='clinicDoctor_dayShift') class ClinicDoctorDayShift(models.Model): clinic_doctor = models.ForeignKey(ClinicDoctor, related_name='to_clinicDoctor') day_shift = models.ForeignKey(DayShift, related_name='to_dayShift') How do I order_by this query visitingQuerySet = ClinicDoctor.objects.filter(doctor_id = doctor_id).prefetch_related('clinicDoctor_dayShift').order_by('doctor__full_name', 'clinic__name') by day in the Day model and shift in Shift model. name and full_name are working but can't get it to work with others. I tried few variations but none works. Another question related to that `querySet' after that query I have this piece of code after it. for vqs in visitingQuerySet: for ab in vqs.clinicDoctor_dayShift.all(): Is that query with all() working on prefetched data or it is making new request to to DB? Is it efficient? Thank you -
How to use Django reverse in tests?
I don't know how to use the reverse function in django.I am getting this, ValueError: dictionary update sequence element #0 has length 1; 2 is required I could hardcode the urls directly that worked fine, but i wanted to do it in standard way. main urls.py urlpatterns = [ url(r'^nmailadmin/', admin.site.urls), url(r'^api/v1/',include('Core.Login.urls',namespace='login')), url(r'^api/v1/mail/',include('Core.Mail.urls',namespace='mail')), ] I have given namespace for login and mail API. When I try to access mail urls like this def test_0list_folders(self): url = reverse('mail:folder_list', kwargs={'server':0}) response = self.client.get('/api/v1/mail/folder_list/0/', follow=True) self.assertEqual(status.HTTP_200_OK, response.status_code) I am getting error like this. ---------------------------------------------------------------------- Traceback (most recent call last): File "/home/next/PycharmProjects/Nmail/Nmail-Server/Core/Mail/tests.py", line 25, in test_0list_folders print(":::::::::::::::::::::: ", reverse('mail:auth_login')) File "/home/next/venv/NmailVenv/lib/python3.6/site-packages/django/urls/base.py", line 91, in reverse return force_text(iri_to_uri(resolver._reverse_with_prefix(view, prefix, *args, **kwargs))) File "/home/next/venv/NmailVenv/lib/python3.6/site-packages/django/urls/resolvers.py", line 436, in _reverse_with_prefix self._populate() Preserving test database for alias 'default'... File "/home/next/venv/NmailVenv/lib/python3.6/site-packages/django/urls/resolvers.py", line 309, in _populate dict(defaults, **pattern.default_kwargs), ValueError: dictionary update sequence element #0 has length 1; 2 is required ---------------------------------------------------------------------- This is my urls file of mail app. urlpatterns = [ url(r'folder_list/(?P<server>\d+)/$', folder_list,name='folder_list'), ]